Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Losing RTTI info after returning from a function

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?

like image 928
Christof Schardt Avatar asked Aug 30 '11 10:08

Christof Schardt


People also ask

Why is runtime type identification RTTI a necessary feature of C++?

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.

How does RTTI work?

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.

Why do we need RTTI?

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.

When to use RTTI?

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.


1 Answers

There was a destructor accidently doing harm to the pointer. After removing this error, the RTTI works as expected.

like image 166
Christof Schardt Avatar answered Sep 28 '22 04:09

Christof Schardt