Why is a reference to a polymorphic class polymorphic?

The snippet below is well known to draw Derived

or something similar.

#include<iostream>
#include<typeinfo>
class Base { public: virtual ~Base(){} };
class Derived : public Base{};
int main()
{
     Derived d;    
     Base& b = d;
     std::cout << typeid(b).name() << '\n';
}

      

But I would like to understand how this can be done from the paragraph § 5.2.8 / 2 in the Standard (N4140). For example, b

it is certainly a glvalue, but the type is Base&

not the same Base

, so I can't tell which b

is polymorphic. What am I missing?

+3


source to share


1 answer


From [expr]

If the expression is originally of type "reference to T" (8.3.2, 8.5.3), the type is promoted to T before any further analysis. An expression denotes an object or function designated by reference, and an expression is an lvalue or xvalue, depending on the expression.

The expression is b

initially of type reference to Base

, so the type is set to Base

. This is an lvalue, which is a glvalue.

From [class.virtual]:

A class that declares or inherits a virtual function is called a polymorphic class.



Base

declares a virtual function, so it is a polymorphic class.

From [expr.typeid]:

When typeid

applied to a glvalue expression whose type is a polymorphic class type (10.3), the result refers to an object std::type_info

that represents the type of the most derived object (1.8) (i.e. the dynamic type) to which the glvalue refers.

Based on the above, we meet the initial conditions (the expression is a glvalue whose type is a polymorphic class type), so we choose the most derived object to which it belongs b

. It will be d

that of the type Derived

.

If b

was Base

instead Base&

, then the most derived object would be b

.

+5


source







All Articles