0

I guess there is something about temporary objects that I don't understand. Given the relationships:

class C {};

class F {
public:
    C getC() { return C(); };
};

class N {
public:
    N( C & base ){};
};

This works:

N n(C());

This doesn't work:

F f;
N n(f.getC()); //compile error

Why?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118

1 Answers1

3

A non-const reference (like B& base) can only bind to an lvalue.

F::getC() returns a C object by value, so the call expression f.getC() is an rvalue, not an lvalue.


The reason that N n(C()); works, however, is due to an unrelated problem.

This does not declare an object. It declares a function named n that returns N and takes a parameter of type "pointer to a function that has no parameters and returns C."

This is one manifestation of a language peculiarity known as the most vexing parse. To change this to declare an object, you'd need one of the following:

N n = C();  // Use copy initialization
N n((C())); // Use more parentheses

Both of these would fail to compile, though, because both would attempt to bind the result of the rvalue expression C() to the non-const reference B& base.


A const reference (like B const& base) can bind to an rvalue, as can an rvalue reference (like B&& base) in C++11.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
  • Sorry, I just edited my code to reduce it to its minimum while you were commenting. Now your comment doesn't reflect the names. Although I understand it, other readers may not. (should I revert it?) – user1440707 Jun 11 '12 at 17:14
  • if the ctor of `N` takes a `C&& base`, then everything works, doesn't it? – Walter Jun 11 '12 at 17:18
  • I'll re-post so the issue and resolution are clear to others. – user1440707 Jun 11 '12 at 17:39
  • Humm.. Stackoverflow won't let me re-post the issue code and resolution code because I'm too new. Using const was the solution. – user1440707 Jun 11 '12 at 17:47
  • No worries. I removed the last instance of `getConcrete()` from your question and updated the answer to match. – James McNellis Jun 11 '12 at 17:49