Search code examples
c++inheritanceundefined-behaviordowncast

Derived class has no extra data members; Is it safe to statically downcast a base object to a derived object?


struct Base {
  int i, j;
};

struct Derived : Base {};

With above scenario, if we do following:

Base b;
auto& d = static_cast<Derived&>(b);
d.i = 1;

Will it be an undefined behaviour?

Note: For some reasons, I can't edit the code of an auto generated google protobuf library. Hence, extending those classes to my custom class, which provides more types & APIs, but it doesn't have any extra data member.


Solution

  • Yes, this is undefined behaviour. Using static_cast to cast from a base class to a derived type which the object is not an instance of is undefined behaviour.

    Additionally, you break the strict aliasing rule by accessing an object through a variable of an invalid type (not the dynamic type, a base class of the dynamic type, char or unsigned char type, and a few other cases).