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.