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?
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.
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