Home >Backend Development >C++ >When is Static Casting for Downcasting in C Safe and When Does it Result in Undefined Behavior?
Downcasting with Static Cast in C
In object-oriented programming, downcasting is a technique used to convert a pointer to a base class into a pointer to a derived class. In C , this can be done using the static_cast operator.
Consider the following code:
class Base { public: Base() {} virtual void func() {} }; class Derived : public Base { public: Derived() {} void func() {} void func_d() {} int a; }; int main() { Base *b = new Base(); std::cout << sizeof(*b) << std::endl; // Prints 4 Derived *d = static_cast<Derived *> (b); // Downcast the base pointer to a derived pointer std::cout << sizeof(*d) << std::endl; // Prints 8 d->func_d(); // Calls the derived class function }
In this code, a base class pointer is initially pointing to a Base object. Using static_cast, we downcast the base pointer to a derived class pointer. The sizeof operator reveals that the derived pointer now points to an object of larger size (8 bytes), which includes the members of the Derived class.
However, it's important to note that the downcasting performed here is invalid. Static_cast allows conversion only if the object pointed to by the base pointer is actually an instance of the derived class. In this case, the Base object is not a Derived object, making the downcast undefined behavior.
According to the C standard, downcasting using static_cast follows these rules:
If these conditions are not met, the cast will result in undefined behavior. Therefore, it's crucial to perform downcasting carefully and ensure the validity of the conversion.
The above is the detailed content of When is Static Casting for Downcasting in C Safe and When Does it Result in Undefined Behavior?. For more information, please follow other related articles on the PHP Chinese website!