c++oopobject-construction

How usage of member initializer list prevents creation of redundant object in c++?


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


Solution

  • Your Example constructor is (implicitly) equivalent to

    Example() : objTest1(Test1(50)), objTest2()
    {
            objTest2 = Test2(50);
    }
    

    That is, the objTest2 object is constructed and initialized once implicitly (this is inserted by the compiler).

    Then you inside the body explicitly construct and initialize a temporary Test2 object that is used to assign to objTest2.


    Also note that in the initializer list objTest1(Test1(50)) constructs a temporary Test1 object, and passes it to the copy-constructor for the initialization of objTest1 (though most compilers should elide this copying). You can simplify it as plain objTest1(50).