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

#include <iostream>

using namespace std;

class Game {


  int goals;

  // constructor used to initialize
  Game() {
    goals = 0;

  // return score

  int getGoals() {
    return goals;

  // increment goal by one

  void incrementGoal() {

int main() {
  Game football;

  cout << "Number of goals when game is started = " << football.getGoals() << endl;


  cout << "Number of goals a little later = " << football.getGoals() << endl;

  return 0;

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.