May 17, 2015 at 10:51am UTC
I was trying some stuff out with covariant return types and I stumbled on something that I don't understand. Have a look at the following code (it does not compile):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#include <iostream>
struct A
{
};
struct B : A
{
};
B create()
{
return {};
}
int main()
{
A& obj = create();
return 0;
}
GCC 4.9.2 produces the following compile time error:
1 2 3
error: invalid initialization of non-const reference of type 'A&' from an rvalue of type 'B'
A& obj = create();
^
Why does the code compile when you const qualify the reference?
Last edited on May 17, 2015 at 10:54am UTC
May 17, 2015 at 12:14pm UTC
A temporary object can't bind to a non-const reference.
May 17, 2015 at 12:28pm UTC
Last edited on May 17, 2015 at 12:28pm UTC