Covariant return type to reference to base, must be const?

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
A temporary object can't bind to a non-const reference.
@Peter87

Thank you very much now I understand!

I Google'd "C++ temporary objects" and I found a very useful article:

https://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=199
Last edited on
Topic archived. No new replies allowed.