Possible Duplicate:
What is this weird colon-member syntax in the constructor?
If I define a class as shown below in C++:
class myclass
{
public:
myclass (unsigned int param) : param_ (param)
{
}
unsigned int param () const
{
return param_;
}
private:
unsigned int param_;
};
What does the constructor definition:
myclass (unsigned int param) : param_ (param) means and the benefit to the code?
myclass (unsigned int param) : param_ (param)
This construct is called a Member Initializer List in C++.
It initializes your member param_ to a value param.
What is the difference between Initializing And Assignment inside constructor? &
What is the advantage?
There is a difference between Initializing a member using initializer list and assigning it an value inside the constructor body.
When you initialize fields via initializer list the constructors will be called once.
If you use the assignment then the fields will be first initialized with default constructors and then reassigned (via assignment operator) with actual values.
As you see there is an additional overhead of creation & assignment in the latter, which might be considerable for user defined classes.
For an integer data type(for which you use it) or POD class members there is no practical overhead.
When do you HAVE TO use member Initializer list?
You will have(rather forced) to use a Member Initializer list if:
Your class has a reference member
Your class has a const member or
Your class doesn't have a default constructor
A code Example that depict the HAVE TO cases:
class MyClass
{
public:
int &i; //reference member, has to be Initialized in Member Initializer List
int j;
const int k; //const member, has to be Initialized in Member Initializer List
MyClass(int a, int b, int c):i(a),j(b),k(c)
{
}
};
class MyClass2:public MyClass
{
public:
int p;
int q;
MyClass2(int x,int y,int z,int l,int m):MyClass(x,y,z),p(l),q(m)
{
}
};
int main()
{
int x = 10;
int y = 20;
int z = 30;
MyClass obj(x,y,z);
int l = 40;
int m = 50;
MyClass2 obj2(x,y,z,l,m);
return 0;
}
MyClass2 doesn't have a default constructor so it has to be initialized through member initializer list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With