C++: The actual constructor

As shown the previous example, we do not actually need a constructor to initialize member data.

Constructor is created to better manage memory allocated for an object.  There is also a Destructor meant for releasing the object back to the memory stack and we will go through that in the later posts.

An example of a constructor is as follows.  Class Country has three member variables. The declaration of constructor can be done inside the class and definition outside the class.

#include <iostream>
#include <string>

using namespace std;

class Country
	string name;
	int noAlbum;
	string latest;

	Country();  //This is the constructor

	name = "Taylor Swift";
	noAlbum = 5;
	latest = "1986";

int main()

	Country ts; // instance declaration
	cout << "Country Singer = " << ts.name << endl;
	cout << "No of Album = " << ts.noAlbum << endl;
	cout << "Her latest album = " << ts.latest << endl;
	cout << endl;

	return 0;

Line 16 is the actual function of the constructor.  Notice how it is defined with the scope operator ::

The constructor function is called when the ts instance is declared in in line 26.  This is done implicitly without the need to specify a calling function.


Series Navigation<< C++: Constructor and data members initialization
C++: A simple experiment on Constructor/Destructor >>