4

Say, I have a class A

Now when I am doing

A a(A()); 

what exactly happens?

7
  • 1
    I would imagine that would be optimized out if it's not being called.
    – chris
    May 29, 2012 at 16:54
  • @chris I'm not so sure. The return value optimization (RVO) is permitted, but what about copies within a single function?
    – user395760
    May 29, 2012 at 16:55
  • @chris...I know of the copy constructor elison concept for the case A a = A(), in this case the default constructor gets called.But in above case neither default nor copy constructor is getting called May 29, 2012 at 16:56
  • possible duplicate of Most vexing parse: why doesn't A a(()); work?
    – Bo Persson
    May 29, 2012 at 17:01
  • 2
    @Radek - Read the question, it is all there! "Why doesn't A a(B()) work?" is a perfect duplicate for "Why doesn't A a(A()) work?".
    – Bo Persson
    May 29, 2012 at 17:11

2 Answers 2

11

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()));
4
  • Use A a{A{}} in C++11 to call the copy ctor if you don't want an extra set of parenthesis.
    – user1203803
    May 29, 2012 at 17:00
  • @FredOverflow Can you explain in little detail :)
    – Invictus
    May 29, 2012 at 17:01
  • @FredOverflow....can you please give an example how to use this function declaration. May 29, 2012 at 17:11
  • Since it's only a declaration, not a definition, you will get a linker error if you try to call the function. Don't get too hung up on this, just add the extra pair of parenthesis and get on with your code ;) May 29, 2012 at 17:16
8

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.

2
  • 3
    is it not an example for the most vexing C++ parse ? I tried with this code: ideone.com/ZVXoT
    – Naveen
    May 29, 2012 at 16:57
  • @Naveen yes, extra set of paranthesis there. May 29, 2012 at 16:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.