A class by itself, such as the Dog class from the "Classes" tutorial, is quite useless. To make good use of such a class for video game programming purposes we need to be able to group several of them, this way we can minimize code when it comes to controling several objects at a time. This can be done by creating an Array of the object just like you would with any other data type. I will be splitting this programming up into several files as well, this will help keep things organized once your programs get bigger. Heres the example code:
#ifndef DOG_H
#define DOG_H 1
class Dog{
public:
Dog();
int getAge();
void setAge(int newValue);
protected:
int age;
};
#endif
This is the header file for the Dog class, it simply holds the prototype for the class, the actual code will be in a seperate file, Dog.cpp. The "#ifndef DOG_H" line is used to make sure Dog isnt declared twice.
#include "Dog.h"
Dog::Dog(){
}
int Dog::getAge(){
return age;
}
void Dog::setAge(int newValue){
age = newValue;
}
Dog.cpp first includes its header file in order to have the prototype for the class, the code here should be familiar from the last lesson.
#include <iostream>
#include "Dog.h"
using namespace std;
int main()
{
Dog myDogs[5];
for (int i = 0; i <= 4; i++)
myDogs[i].setAge( i * 2);
for (int i = 0; i <= 4; i++)
cout << "Dog number " << i << " is " << myDogs[i].getAge() << " years old!\n";
delete [] myDogs;
return 0;
}</iostream>
main.cpp holds the code for the actual program. It only needs to include the header file for the class, not the actuall code file (Dog.cpp). Dog myDogs[5]; simply creates an array of 5 Dogs, just like using any other built in data type.
In order to access each individual Dog, simply include its index number in the brackets, and use it as you would any normal class. This example simply sets their age and displays it.
-KR