In fact, the Standard (C++11) uses the term polymorphic class type, rather than polymorphic type when it describes the behaviour of typeid
:
Firstly, here it describes what happens when typeid
is applied to an lvalue of class type (i.e. the case when it does what you expect):
(§5.2.8/2) When typeid
is applied to a glvalue expression whose type is a polymorphic class type (10.3), the result refers to a std::type_info
object representing the type of the most derived object (1.8) (that is, the dynamic type) to which the glvalue refers. [...]
But when you apply it to a pointer (i.e. not to an lvalue of class type), the rule below applies:
(§5.2.8/3) When typeid
is applied to an expression other than a glvalue of a polymorphic class type, the result refers to a std::type_info
object representing the static type of the expression. [...]
It says you get the static (not the dynamic) type, i.e. you get the declared type of the pointer, not the type of object it is actually pointing to.
So, yes, pointers have polymorphic characteristics as you describe, but not when it comes to the result of typeid
.
(In fact, all of their polymorphic characteristics (including, in particular, polymorphic member function calls) only manifest themselves when some sort of explicit dereferencing, either using *
or using ->
, is involved. So you should really say that the pointers themselves aren't polymorphic; only the objects you get when you dereference them are.)
struct A {}; struct B : A {}; int main() { A* ap = new B; }
Here,ap
is declared as pointer to base class, but it actually points to an object of the derived class. – jogojapan