0

I've looked quiet some time but I find it hard to find an answer to this problem* which I think someone with more c++ experience finds pretty obvious.

Consider this class:

class A {
    public:
        A( const char * name ){}
};

class X {
    public:
        X( A const&a ) {}
};

class Y {
    public:
        Y( A &a ) {}
};

And this code:

A a( "1" );
X x1( a ); // Works

X x2( A( "2" ) ); // Works

Y y3( A( "3" ) ); // Error!

So why can I pass an object by non-const reference to an Constructor but not an anonymous one?

And is there another way to write something like this to have these objects constructed on the heap**?

Car car( Person( "Mike" ), Person( "Sandra" ) );

Thanks in advance!


*) Hard because searching for "const anonymous reference constructor" yields many but mostly unrelated answers. **) I'm doing embedded stuff...

Scheintod
  • 7,953
  • 9
  • 42
  • 61
  • _So why can I pass an object by non-const reference to an Constructor but not an anonymous one?_ On that contrary. Temporary **can** bind to a `const` reference, but **can't** bind to a non-`const` reference. Your 2nd/3rd examples demonstrates just that. – Algirdas Preidžius Jan 23 '17 at 16:48
  • Temporary cannot bind to non-const reference. – Jarod42 Jan 23 '17 at 16:48
  • *"const temporary reference constructor"* gives better results. – Jarod42 Jan 23 '17 at 16:51

0 Answers0