ClassName::ClassName() {
AnotherClass class2; // this will create local variable only
}
If AnotherClass
will have default constructor, then it will be called for the class2
object by compiler.
If you want to call parametrized constructor then you will have do it in following way:
ClassName::ClassName() :
class2(arguments)
Why to use and How to use initializer list :
Consider the following example:
// Without Initializer List
class MyClass {
Type variable;
public:
MyClass(Type a) { // Assume that Type is an already
// declared class and it has appropriate
// constructors and operators
variable = a;
}
};
Here compiler follows following steps to create an object of type MyClass
- Type’s constructor is called first for “a”.
The assignment operator of “Type” is called inside body of MyClass() constructor to assign
variable = a;
And then finally destructor of “Type
” is called for “a
” since it goes out of scope.
Now consider the same code with MyClass
() constructor with Initializer List
// With Initializer List
class MyClass {
Type variable;
public:
MyClass(Type a):variable(a) { // Assume that Type is an already
// declared class and it has appropriate
// constructors and operators
}
};
With the Initializer List, following steps are followed by compiler:
- Copy constructor of “
Type
” class is called to initialize : variable(a)
. The arguments in initializer list are used to copy construct “variable
” directly.
- Destructor of “
Type
” is called for “a
” since it goes out of scope.
As we can see from this example if we use assignment inside constructor body there are three function calls: constructor + destructor + one addition assignment operator call. And if we use Initializer List there are only two function calls: copy constructor + destructor call.
This assignment penalty will be much more in “real” applications where there will be many such variables.
Few more scenarios, where you will have to use initializer list only:
- Parametrized constructor of base class can only be called using Initializer List.
- For initialization of reference members
- For initialization of non-static const data members