C++ object creation and constructor

I will comment on the third one first:

Foo obj3=Foo(args);

It doesn't use operator= which is called copy-assignment. Instead it invokes copy-constructor (theoretically). There is no assignment here. So theoretically, there is two objects creation, one is temporary and other is obj3. The compiler might optimize the code, eliding the temporary object creation completely.

Now, the second one:

Foo obj2;         //one object creation
obj = Foo(args);  //a temporary object creation on the RHS

Here the first line creates an object, calling the default constructor. Then it calls operator= passing the temporary object created out of the expression Foo(args). So there is two objects only the operator= takes the argument by const reference (which is what it should do).

And regarding the first one, you're right.


Your terminology is a bit confusing.

The objects obj, obj2 obj3 are not called "temporary objects". Only the instance that is created in line 3 before being assign to obj is a temporary object.

Also, you don't create "a copy of Foo", you create either "an instance of Foo" or "an object of type Foo".


  1. Yes, Foo obj(args) creates one Foo object and calls the ctor once.

  2. obj2 is not considered a temporary object. But just like 1 Foo obj2 creates one object and calls the Foo ctor. Assuming that you meant obj2 = Foo(args) for the next line, this line creates one temporary Foo object and then calls obj2.operator=(). So for this second example there is only a single temporary object, a single non-temporary, Foo ctors are called twice (once for the non-temporary, once for the temporary) and the operator=() is called once.

  3. No, this line does not call operator=(). When you initialize obj3 using the = syntax it is almost exactly as if you had used parentheses instead: Foo obj3(Foo(args)); So this line creates a temporary object, and then calls the Foo copy ctor to initialize obj3 using that temporary object.