1
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.

iammilind
  • 68,093
  • 33
  • 169
  • 336
  • @pSoLT, thanks. [Downcasting using the Static_cast in C++](http://stackoverflow.com/q/6322949/514235). It's strongly related. In this Qn, I will be more interested to know when the sizes are potentially same. BTW, if someone feels that the accepted answer in that post is also catering this Qn, then it will be great if someone can explain in easier language. I just got lost while reading that passage from the standard. :-) – iammilind Jan 10 '17 at 10:55

1 Answers1

4

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).

TartanLlama
  • 63,752
  • 13
  • 157
  • 193
  • I think the practical should also be noted. I can't think of any compiler that would detect the downcast and do Harmful Things. An example of (existence of) such behavior would be greatly appreciated. – Cheers and hth. - Alf Jan 10 '17 at 14:48
  • 1
    @Cheersandhth.-Alf: Whether or not any of today's compiler writers would behave in odd fashion, it is fashionable for compilers to try to identify cases where certain inputs would cause Undefined Behavior and then eliminate conditional tests which would always return the same value in all other cases. I'm skeptical that such "optimizations" would offer a cost/benefit ratio that's anywhere near as good as what could be achieved with directives to invite compilers to make certain assumptions about input values, but I don't control the fashions. – supercat Jan 10 '17 at 19:21