In C , downcasting refers to the conversion of a base class pointer or reference to a derived class pointer or reference. One way to perform downcasting is through the use of the static_cast<> operator.
Consider the following code:
class base { base(); virtual void func(); }; class derived : public base { derived(); void func(); void func_d(); int a; }; int main() { base *b = new base(); sizeof(*b); // Gives 4. derived *d = static_cast<derived*>(b); sizeof(*d); // Gives 8- means whole derived obj size..why? d->func_d(); }
In this example, we have a base class base and a derived class derived. We create a base class pointer b pointing to an object of type base. Using static_cast<>, we attempt to cast b to a derived class pointer d.
The confusing question here is why the derived class pointer d has access to the entire derived class object, despite b pointing to a base class object.
However, it's crucial to understand that using static_cast<> to cast a pointer to a type that it doesn't belong to is considered undefined behavior in C .
According to the C standard ([expr.static.cast]), a static cast to a derived class pointer from a base class pointer is only allowed if the following conditions are met:
If any of these conditions are not met, the result of the cast is undefined.
In the given code, since b points to a pure base class object, there is no enclosing derived class object to point to. Therefore, the behavior of the program becomes unpredictable and should not be relied upon.
The above is the detailed content of Why Does `static_cast` to a Derived Pointer Seem to Access the Entire Derived Object in C When the Original Pointer Points to a Base Class Object?. For more information, please follow other related articles on the PHP Chinese website!