You are here

C++ constructor example

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

C++ constructor program example

  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. class Game {
  6.  
  7. private:
  8.  
  9.   int goals;
  10.  
  11. public:
  12.   // constructor used to initialize
  13.   Game() {
  14.     goals = 0;
  15.   }
  16.  
  17.   // return score
  18.  
  19.   int getGoals() {
  20.     return goals;
  21.   }
  22.  
  23.   // increment goal by one
  24.  
  25.   void incrementGoal() {
  26.     goals++;
  27.   }
  28. };
  29.  
  30. int main() {
  31.   Game football;
  32.  
  33.   cout << "Number of goals when game is started = " << football.getGoals() << endl;
  34.  
  35.   football.incrementGoal();
  36.   football.incrementGoal();
  37.  
  38.   cout << "Number of goals a little later = " << football.getGoals() << endl;
  39.  
  40.   return 0;
  41. }

The Game class contains a member goals which stores the number of goals. Game() constructor is used to initialize the number of goals which are zero initially. Game class object football is created and number of goals are printed just after the object is created and goals are incremented using incrementGoal function.