C++: Constructor and data members initialization

This entry is part 23 of 61 in the series C++

In our example on data member, we have a part that initializes the data members of the class.  This can be done using constructor of a class.

The example is as shown below.  In line 19, we are creating an instance of the class Country. When creating this instance, the constructor will be called so as to initialize the data members.

However, in the example, I actually did not explicitly declare a constructor. The C++ program will, however, lazily create a constructor itself and initialize the data members to null values.

#include <iostream>
#include <string>

using namespace std;

class Country

	string name;
	int noAlbum;
	string latest;


int main()

	Country ts; // instance declaration

	ts.name = "Taylor Swift"; // member initialization
	ts.noAlbum = 5;
	ts.latest = "1986";

	cout << "\n Country Singer = " << ts.name;
	cout << "\n No of Album = " << ts.noAlbum;
	cout << "\n Her latest album = " << ts.latest;
	cout << "\n";

	return 0;

We will look at the actual constructor in the next example.

Series Navigation<< C++: An instance of an object
C++: The actual constructor >>