Home >Backend Development >C++ >When is Static Casting for Downcasting in C Safe and When Does it Result in Undefined Behavior?

When is Static Casting for Downcasting in C Safe and When Does it Result in Undefined Behavior?

Barbara Streisand
Barbara StreisandOriginal
2024-11-28 02:50:11398browse

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:

  1. The base class pointer must point to an object that is derived from the target class.
  2. The target class must not be a virtual base class of the base class.
  3. The resultant pointer will point to the base class subobject within the derived object.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn