You are here

C++ constructor example

C++ constructor example programs: Constructor are functions having name as that of class. They do not have return type and are used to initialize objects.

C++ constructor program example

#include <iostream>
 
using namespace std;
 
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.