Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What will happen if dynamic_cast<void*> casts an object with underlying non-most-derived class?

We know that dynamic_cast<void*> will cast a pointer to the pointer to the most derived object; but what if the underlying object is not the most derived? For example:

class BaseClass { public: virtual void dummy() { std::cout << "Base\n"; } };

class DerivedClass : public BaseClass {
    int a{}; 
public:
    void dummy() { std::cout << "Derived\n"; } 
};
class MostDerivedClass : public DerivedClass {
    int b{}; 
public:
    void dummy() { std::cout << "Most\n"; } 
};

BaseClass* basePtr_d = new DerivedClass, *basePtr_md = new MostDerivedClass;
DerivedClass* derivedPtr = 
    dynamic_cast<DerivedClass*>(basePtr_d); // right
MostDerivedClass* mostDerivedPtr = 
    dynamic_cast<MostDerivedClass*>(basePtr_md); // right
MostDerivedClass* mostDerivedPtr2 = 
    static_cast<MostDerivedClass*>(dynamic_cast<void*>(basePtr_md)); // right
DerivedClass* derivedPtr2 = 
    static_cast<DerivedClass*>(dynamic_cast<void*>(basePtr_d)); // What happens??

What happens for the last case?

like image 330
o_oTurtle Avatar asked Sep 02 '25 02:09

o_oTurtle


1 Answers

The last case is the same as the previous case. You have a BaseClass *, you do a pointer conversion which gives you the value of a pointer to the most derived object, and then you statically cast that value to the appropriate type. At no point does the type MostDerivedClass get involved in these conversions.

"most derived class" is not a global property of the types in your program. It refers to the particular object you have a pointer or reference to. For objects that you get from new, it is the type that was used in the new expression.

basePtr_d points to the BaseClass subobject of a DerivedClass instance, and basePtr_md points to the BaseClass subobject of a MostDerivedClass instance.

like image 103
Caleth Avatar answered Sep 04 '25 16:09

Caleth