Question

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.

Was it helpful?

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;

OTHER TIPS

The first case is quite simple - constructs an instance using the default constructor.

The second class is Constructing an anonymous object and then calling the copy constructor. Notice that here the = is not assignment, it's similar to (but not identical) writing:

TestClass t(TestClass());

We can verify that this needs the copy constructor to be available by making it unavailable, e.g.:

#include <iostream>

struct TestClass {
  TestClass() { std::cout << "Ctor" << std::endl; }
  TestClass(const TestClass&)  = delete;
};

int main() {
  TestClass t = TestClass();
}

Which fails to compile because of the deleted copy constructor. (In C++03 you can use private: instead).

What's actually happening most likely though is that your compiler is doing Return value optimisation, whereby it's allowed to ommit the call to the copy constructor entirely provided a suitable one exists and would be accessible.

In the first one, you are calling the default constructor implicitly. And in the second one you're calling it explicitly.

The latter one could call copy constructor and thus requires one to be public.

Edit: I certainly drew far too big conclusions from the type name you used. The sentence above only applies for class-types (i.e. not POD). For POD types, the former leaves the variable uninitialized, while the latter initializes it with so-called "default" value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top