I have a question regarding difference in initializing an object with and without constructor member initializer list.
In the following code snippet there are two classes Test1
and Test2
each with two constructors, objects of these two classes are created in the default constructor of another class Example
.
Object of Test1
is created with one parameter in member initializer list, whereas that of Test2
is created with one parameter inside constructor body of Example
.
class Test1 {
public:
Test1() { cout << "Test1 is created with no argument"; }
Test1(int a) { cout << "Test1 is created with 1 argument"; }
};
class Test2 {
public:
Test2() { cout << "Test2 is created with no argument"; }
Test2(int a) { cout << "Test2 is created with 1 argument"; }
};
class Example {
public:
Test1 objTest1;
Test2 objTest2;
Example() : objTest1(Test1(50))
{
objTest2 = Test2(50);
}
};
int main()
{
Example e;
}
The output of the above code is :
Test1 is created with 1 argument
Test2 is created with no argument
Test2 is created with 1 argument
My Questions
- Why does object of
Test2
is created twice? (The one which is created without member initializer.) - What had happened to the redundant object of
Test2
? Does it still occupies some memory? - How does member initializer list works in initializing class member variables?
- Is there is any performance benefit in using member initializer list? (As Test1 is created only once)