Search code examples
c++constructorcopy-constructorexplicitcopy-initialization

Explicit and non-explicit constructors


class Test
    {
    public:
        Test(int i) { cout<<"constructor called\n";}
        Test(const Test& t) { cout<<" copy constructor called\n";}
    };
 class Test1
        {
        public:
            Test1(int i) { cout<<"constructor called\n";}
            explicit Test1(const Test1& t) { cout<<" copy constructor called\n";}
        };

    int main()
    {
        Test t(0);  
        Test u = 0;
        //Test1 t1(0);   Line 1
        //Test1 u1 = 0;  Line 2

    }

I observe different outputs. Case 1: When Line 1 and Line 2 are commented the o/p is : constructor called constructor called

Case 2: When Line 1 and Line 2 are uncommented : then compilation error

Can someone explain the outputs and the reason for that. Also can someone tell if operator= actually ends up calling the copy constructor or not.


Solution

  • Your problem lies in that explicit constructor down there, plus a slight misunderstanding of object initialization.

    According to this, the expression:

    Type variableName = value;
    

    Will always perform copy initialization of such an object, that means that:

    Test1 u1 = 0;
    

    Will effectively call the overloaded constructor Test1::Test1(const Test1&), with argument Test1(int), thus resulting in u1::Test1(Test1(0)).

    And, of topping, because you declare the copy constructor as explicit, the copy-style initialization will fail, but this:

    Test1 t1(0);
    

    Will compile, because this expression invokes direction initialization, and even if Test1(int) would be marked as explicit, direct initialization is explicit, so every piece matches.