Given a class and subclass:
class Event {...}
class Note : public Event {...}
A Note is Cloned and stored in a pointer within a function f(). The type-information is preserved in the pointer and can be recovered by dynamic_cast:
void f()
{
pEvent = pNote->Clone(); // create a clone of a Note
ASSERT(dynamic_cast<Note*>(pEvent)); // check the pointer, here it works
}
Now, after returning from f() the type-information is lost:
f();
ASSERT(dynamic_cast<Note*>(pEvent)); // -> "Access violation - no RTTI-data"
The VS-debugger shows a valid pointer-value (unchanged), but not the derived class,
other than while beeing in the f()
-scope.
How can the RTTI-info for a pointer be lost when returning from a function?
Run-time type identification (RTTI) lets you find the exact type of an object when you have only a pointer or reference to the base type. This can be thought of as a “secondary” feature in C++, a pragmatism to help out when you get into messy situations.
C++ has three components supporting RTTI: The dynamic_cast operator generates a pointer to a derived type from a pointer to a base type, if possible. Otherwise, the operator returns 0 , the null pointer. The typeid operator returns a value identifying the exact type of an object.
In C++, RTTI (Run-time type information) is a mechanism that exposes information about an object's data type at runtime and is available only for the classes which have at least one virtual function. It allows the type of an object to be determined during program execution.
RTTI is available only for classes that are polymorphic, which means they have at least one virtual method. In practice, this is not a limitation because base classes must have a virtual destructor to allow objects of derived classes to perform proper cleanup if they are deleted from a base pointer.
There was a destructor accidently doing harm to the pointer. After removing this error, the RTTI works as expected.
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