Home >Backend Development >C++ >How Can `static_cast` Seemingly Allow Access to a Derived Class\'s Members When Downcasting a Base Pointer to a Distinct Base Object?
Downcasting Using the static_cast Operator: Demystifying Undefined Behavior
Consider the following concern:
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 scenario, casting the base pointer to a derived pointer using static_cast has seemingly allowed access to the full derived object's size and function. However, this raises the question: how is this possible if the base pointer originally pointed to a distinct base object?
Understanding the Undefined Behavior
The answer lies in the nature of static_cast and its impact on dynamic objects. Downcasting using static_cast to a type that the object does not actually have is classified as undefined behavior. The consequences of undefined behavior can vary dramatically, including allowing unexpected access to the derived class member function func_d() in this case.
The Rule of Downcasting
According to the C standard (section 5.2.9), downcasting using static_cast follows a specific rule:
In our example:
The unexpected success of calling d->func_d() is a consequence of this undefined behavior. Do not rely on the ability to access derived class members after an unsafe downcast.
The above is the detailed content of How Can `static_cast` Seemingly Allow Access to a Derived Class\'s Members When Downcasting a Base Pointer to a Distinct Base Object?. For more information, please follow other related articles on the PHP Chinese website!