Close

Member initialization list in C++

You all know that in C++, constructors are used to create an object. We normally initialize all the data members with some valid data in the constructor. We generally write code similar to the following and think that m_data variable is being initialized where as it is actually being assigned.

class MyClass
{
public:
Myclass(int d)
{
m_data = d;
}
private:
int m_data;
}
 

To actually initialize a data member, we need to use member initialization list in C++. Using member initialization list, the constructor is written as follows

class MyClass
{
public:
Myclass(int d):m_data(d)
{
}
private:
int m_data;
}
 

Here we specified the member initialization list after constructor name followed by colon (:) If multiple members are present, they are separated by Comma. like m_data1(d1), m_data2(d2). In this case the members are initialized before entering the constructor itself.

What happens in the first case?  The default constructor (that is provided by the compiler) is called to initialize non-primitive data types before entering the written constructor. All the primitive type data members like int, char, float are not guaranteed to get initialized in the default constructor.

Leave a Reply

Your email address will not be published. Required fields are marked *