Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ dynamic_cast - polymorphic requirement and downcasting

In the following code, while constructing obj in case 1, we construct a derived class object too, but its member functions are just inaccessible to obj. So while downcasting (i.e., in case 2), using obj as source, we have the constructed derived in it already. Why would obj need to be polymorphic?

If I confused you with my above description, why doesn't obj need to be polymorphic when upcasting, but while downcasting it does need to be polymorphic while using dynamic_cast?

class base
{
public:
    base()
    {
        cout<< " \n base constructor \n";
    }
};

class derived : public base
{
public:
    derived()
    {
        cout << " \n derived constructor \n";
    }
};

base *obj = dynamic_cast<base*> (new derived); // case 1: explicitly upcasting
derived *OBJ = dynamic_cast<derived*> (obj);   // case 2: error
like image 206
Mahesh Avatar asked Jan 10 '11 08:01

Mahesh


People also ask

Does dynamic_cast required Rtti?

Note. You are permitted to use dynamic_cast without --rtti in cases where RTTI is not required, such as dynamic cast to an unambiguous base, and dynamic cast to (void *) . If you try to use dynamic_cast without --rtti in cases where RTTI is required, the compiler generates an error.

Is Downcasting safe C++?

A downcast is a cast from a base class to a class that's derived from the base class. A downcast is safe only if the object that's addressed at runtime is actually addressing a derived class object.

Why dynamic_cast is used in C++?

The primary purpose for the dynamic_cast operator is to perform type-safe downcasts. A downcast is the conversion of a pointer or reference to a class A to a pointer or reference to a class B , where class A is a base class of B .

How dynamic_cast is implemented in compiler?

Consider this simple hierarchy: class Base { public: virtual ~Base() { } }; class Derived : public Base { }; Trying to downcast Base* p to Derived* is possible using dynamic_cast<Derived*>(p) . I used to think dynamic_cast works by comparing the vtable pointer in p to the one in a Derived object.


1 Answers

In order for dynamic_cast to work the object needs to be polymorphic. The reason for this is that dynamic_cast needs somewhere to store the type information that is will use to perform the cast, and it does this by storing the information alongside the vtable for the class. In order for there to be a vtable you need to make at least one of your methods virtual.

The easiest way around this is to flag the base class destructor as virtual.

Upcasting (ie derived to base) doesn't needs a cast as the compiler is able to check that the cast would work at compile time. However, the same isn't true when downcasting.

like image 166
Sean Avatar answered Oct 04 '22 21:10

Sean