Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typeid for polymorphic pointers?

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)

like image 229
user2465355 Avatar asked Jun 09 '13 14:06

user2465355


People also ask

What is the use of Typeid () function?

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.

Is Typeid a runtime?

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.


1 Answers

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.)

like image 119
jogojapan Avatar answered Oct 15 '22 18:10

jogojapan