C++ constructor program example
#include <iostream.h>
class Game {
private:
int goals;
public:
// constructor used to initialize
Game() {
goals = 0;
}
// return score
int getGoals() {
return goals;
}
// increment goal by one
void incrementGoal() {
goals++;
}
};
int main() {
Game football;
cout << "Number of goals when game is started = " << football.getGoals() << endl;
football.incrementGoal();
football.incrementGoal();
cout << "Number of goals a little later = " << football.getGoals() << endl;
return 0;
}
Game class contains a member goals which stores the number of goals. Game() constructor is used to initialize number of goals which are zero initially. Game class object football is created and number of goals are printed just after object is created and goals are incremented using incrementGoal function.