Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do C++ POD types have RTTI?

Tags:

c++

rtti

vtable

As I understand how RTTI is implemented in various C++ compilers (such as GCC), a pointer to the type_info data is stored in the vtable data of each class.

And also as mentioned here, POD type may not have a vtable.

But if POD types may not have a vtable then where is the pointer to the type_info stored? I know it is implementation-specific, but it would be better to be aware of a C++ compiler (such as GCC) internals.

like image 323
Sadeq Avatar asked Feb 11 '16 14:02

Sadeq


People also ask

When to use RTTI?

You can use RTTI only with a class hierarchy that has virtual functions. The reason for this is that these are the only class hierarchies for which you should be assigning the addresses of derived objects to base-class pointers. RTTI works only for classes that have virtual functions.

Why is RTTI a necessary feature of C++?

RTTI, Run-Time Type Information, introduces a [mild] form of reflection for C++. It allows to know for example the type of a super class, hence allowing to handle an heterogeneous collection of objects which are all derived from the same base type.

How RTTI works in C++?

In C++ the RTTI is a mechanism, that exposes information about an object's datatype during runtime. This feature can be available only when the class has at least one virtual function. It allows the type of an object to be determined when the program is executing.

Which operators can be used to implement runtime type identification?

There is an operator, called typeid, which can be used to get the runtime information of an object. This operator returns a type_info instance. The std::type_info is a class that holds implementation-specific information of a type, such as type name, and means to compare the equality of two types.


1 Answers

There are two kinds of types (for the purposes of RTTI): polymorphic types and non-polymorphic types. A polymorphic type is a type that has a virtual function, in itself or inherited from a base class. A non-polymorphic type is everything else; this includes POD types, but it includes many other types too.

If you have a pointer/reference to a polymorphic type T, and you call typeid on it, the type_info you get back is not necessarily the type_info you would get back for typeid(T{}). Instead, it is the true dynamic type of the object: the most derived class.

If you have a pointer/reference to a non-polymorphic type T, typeid will always return the type_info for T itself. Non-polymorphic types always assume that the pointer/reference is exactly its static type.

POD types are non-polymorphic, but a huge number of other types are non-polymorphic as well.

like image 166
Nicol Bolas Avatar answered Nov 01 '22 20:11

Nicol Bolas