I don't understand why pointers aren't polymorphic types, since we can use base class pointers, which are pointing to derived classes, to call derived class' virtual function. This suggests at runtime, the system can determine if a pointer is polymorphic, doesn't it?
(This is a follow-up question from typeid for polymorphic types)
The typeid operator allows the type of an object to be determined at run time. The result of typeid is a const type_info& . The value is a reference to a type_info object that represents either the type-id or the type of the expression, depending on which form of typeid is used.
Since typeid is applied to a type rather than an object, there is no runtime type information, so that overhead won't be a problem.
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 astd::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 astd::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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With