Constructors initialize variables at the creation of the class.
for instance:
Code:
class town
{
public:
int population;
town(int populationI);
};
town::town(int populationI)
{
population = populationI;
}
// The call
town myTown(6) ; //Would create a town with 6 people
That is an example of a constructor(which you really don't need with a simplistic class).
Private versus Public
You could choose to make your member variables private, instead of public. You can do it just as you declare the variable public --- private: You then need an accessor function to access the variable(the regular town.population will not work) - you can define the funtion the same way as you defined the constructor.
Header set-up
For the header set-up, you should have two files - one for the definitions, one for the declaration.
The header/cpp file would look something like this:
Code:
/*********town.h*********/
#ifndef TOWN_H
#define TOWN_H
class town
{
public:
town(int populationI);
private:
int population;
};
#endif
/*********town.cpp*********/
town::town(int populationI)
{
population = populationI;
}
/*********main.cpp*********/
include <iostream>
int main()
{
town myTown(5);
}
Ask any questions you want