Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine actual object type at runtime in C++;

Lets say we have a class hierarchy. At the bottom we have Base and at the top Derived. How to determine object class even if it is converted to base class pointer.

Base* b = new Derived():

typeid(b).name(); // i want this to tell me that this is actually derived not base object

is there any way other than manual implementation of string field or such and virtual get function?

PS: I talking about compiler-independent solution

like image 881
user1079475 Avatar asked Apr 09 '13 09:04

user1079475


People also ask

How do you find the type of object in runtime?

Object. getClass() method is used to determine the type of object at run time.

What is runtime type information in C?

Run-time type information (RTTI) is a mechanism that allows the type of an object to be determined during program execution. RTTI was added to the C++ language because many vendors of class libraries were implementing this functionality themselves. This caused incompatibilities between libraries.

How can you determine at run time the type of an object C++?

The simplest way to determine the runtime type of an object using a pointer or reference is to use the runtime cast that verifies that the cast is valid. This is particularly useful when we want to cast a base class pointer to its derived type.

How do you check if an object is a certain type in C#?

To determine whether an object is a specific type, you can use your language's type comparison keyword or construct. For example, you can use the TypeOf… Is construct in Visual Basic or the is keyword in C#. The GetType method is inherited by all types that derive from Object.


1 Answers

make sure the base class has at least one virtual method, include <typeinfo> and use your current code just with an additional dereferencing, typeid(*b).name().


in passing, note that a typeid call is the one place in C++ where you can dereference a nullpointer with well-defined behavior, which implies that it can throw an exception:

C++11 §5.2.8/2:
“If the glvalue expression is obtained by applying the unary * operator to a pointer and the pointer is a null pointer value (4.10), the typeid expression throws the std::bad_typeid exception (18.7.3).”

like image 68
Cheers and hth. - Alf Avatar answered Oct 06 '22 23:10

Cheers and hth. - Alf