Sunday 26 July 2015

  • Sunday, July 26, 2015


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.
Related Posts Plugin for WordPress, Blogger...

Vacancy

RBI has announced the recruitment for 134 GRADE B OFFICERS.
 The examination will be in two phases.
 The detailed advertisement will be published on 5th October.

Popular Posts