Search code examples
c++constructorinitializationdefault-constructorcopy-assignment

For a class, what is the difference between default-initialization, and copy-initialization to a value-initialized prvalue?


What is the difference between this:

TestClass t;

And this:

TestClass t = TestClass();

I expected that the second might call the constructor twice and then operator=, but instead it calls the constructor exactly once, just like the first.


Solution

  • TestClass t;
    

    calls the default constructor.

    TestClass t = TestClass();
    

    is a copy initialization. It will call the default constructor for TestClass() and then the copy constructor (theoretically, copying is subject to copy elision). No assignment takes place here.

    There's also the notion of direct initialization:

    TestClass t(TestClass());
    

    If you want to use the assignment operator:

    TestClass t;
    TestClass s;
    t = s;