Kundan Kumar
Kundan Kumar

Reputation: 2002

Why copy constructor not getting called in this case

Say, I have a class A

Now when I am doing

A a(A()); 

what exactly happens?

Upvotes: 4

Views: 176

Answers (2)

fredoverflow
fredoverflow

Reputation: 263240

Despite appearances, A a(A()); is not an object definition. Instead, it declares a function called a that returns an A and takes a pointer to a function taking nothing and returning an A.

If you want an object definition, you have to add another pair of parenthesis:

A a((A()));

Upvotes: 11

Luchian Grigore
Luchian Grigore

Reputation: 258618

If written correctly - A a((A())) - the compiler creates the temporary directly in the constructor context to prevent an extra copy. It's called copy elision. Look this up, along with RVO and NRVO.

From your comment:

A a = A();

this is exactly equivalent to

A a((A())); // note extra pair of parenthesis 

As @Naveen correctly pointed out, A a(A()); is subject to most vexing parse, so you need an extra set of paranthesis there to actually create an object.

Upvotes: 8

Related Questions