3

I'm trying to pass a temporary object to another object constructor for the second object to take ownership of the generated object. My code is something like this

class A {
};

class B {
    A a;
    public:
        B(A && _a) : a(_a) {}

        void test(){ }
};

int main(int argc, const char *argv[])
{
    B b(A());
    b.test();
    return 0;
}

but I'm getting this error that I'm not able to understand

$ g++ -std=c++0x main.cpp  
main.cpp: In function 'int main(int, const char**)': 
main.cpp:15:7: error: request for member 'test' in 'b', which is of non-class type 'B(A (*)())'

Perhaps it is just a silly syntax error, but in case it is not, how would you defined such constructor for taking ownership of some created resource?

Thanks

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
tonicebrian
  • 4,715
  • 5
  • 41
  • 65
  • It is a syntax error. You declared a function `b`, taking a zero-adic function that returns `A`, and returning `B`. – Fred Foo Nov 27 '11 at 17:32
  • 1
    possible duplicate of [constructor invocation mechanism](http://stackoverflow.com/questions/4283576/constructor-invocation-mechanism) – Mat Nov 27 '11 at 17:32
  • 1
    See also http://stackoverflow.com/questions/6690256/why-can-this-code-elide-a-copy, http://stackoverflow.com/questions/180172/why-is-it-an-error-to-use-an-empty-set-of-brackets-to-call-a-constructor-with-no – Mat Nov 27 '11 at 17:33

1 Answers1

3

You got caught by what is known as C++'s most vexing parse. Your line

B b(A());

does not define an object b of type B initialized with a temporary object of type A, but declares a function named b taking an unnamed argument of type (pointer to a) function with no arguments and returning A (thus the type of b's argument is declared as the function type A() and decays to the pointer-to-function type A(*)() which you can see in the error message), and returning a B.

The simplest way around is to change that line to

B b = B(A());

In C++11, the best option is to use the new initializer syntax and write

B b { A() };
celtschk
  • 19,311
  • 3
  • 39
  • 64