C++ Tutorials



Tutorials > C++ > Constructors

View Full Source


When creating an object, you may want each object to have default values assigned to its variables or you would like some action to occur. This can be achieved using contructors.

Contents of main.cpp :

#include <iostream>
#include <stdlib.h>

using namespace std;

First we create the class as per normal.

class Player
public :

A constructor is like a normal method except that it has no return type and it has the same name as the class. A constructor can take a number of parameters and the constructor can also be overloaded. This is shown below.

	Player(int h);
	Player(int h, int m);

The rest of the class is completed below.

	int health;
	int mana;

	void attack()
	{ cout << "Player Attacks" << endl; }

Our first constructor assigns a value of 100 to health and 50 to mana.

	health = 100;
	mana = 50;

Our second constructor sets the health value to a value specified by the parameter and the mana is set to 50.

Player::Player(int h)
	health = h;
	mana = 50;

The third constructor uses both parameters to determine the variable values. You may also notice something different about this constructor. As initializing variables is so common, an initializing list is available. You can place a : after the constructor signature followed by a list of variables separated by commas.

The value you want to assign to the variable must be placed within brackets after the variable's name. This may help your code to become more readable. This technique could also have been used in the constructors above.

Player::Player(int h, int m) :

int main()

The first object we create will be initialized with health of 100 and mana of 50. If no parameters are specified after the object's name, the default constructor (one with no parameters) is used.

	Player bob;
	cout << "Bob : "
		<< << " " << bob.mana << endl;

Adding (50) after fred will call the second constructor, initializing the object with 50 for both health and mana.

	Player fred(50);
	cout << "Fred : "
		<< << " " << fred.mana << endl;

The last object is initialized with 30 health and 80 mana.

	Player sally(30, 80);
	cout << "Sally : "
		<< << " " << sally.mana << endl;


	return 0;

Constructors are very useful when creating classes. Not only can they be useful for taking specific actions when an object is created, more than one constructor can be made, allowing different actions to be taken with different parameters.

Please let me know of any comments you may have : Contact Me

Source Files : Visual Studio Dev-C++ Unix / Linux

< Tutorial 46 - Classes Tutorial 48 - Destructors >

Back to Top

All Rights Reserved, © Zeus Communication, Multimedia & Development 2004-2005

Read the Disclaimer