Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downcasting non-polymorphic types?

Tags:

c++

c++20

Please consider the following C++20 program:

struct B { B(); private: int whatever; }; // non-aggregate
struct D : B { D(); int x; private: int whatever2; }; // non-aggregate

int main() {
   D* d = new D;
   d->x = 42;
   B* b = (B*) d;
   D* d2 = (D*) b;
   return d2->x;
}

Is this program ill-formed or have undefined behaviour?

That is, is it allowed to cast a pointer to the base subobject of a derived object of non-polymorphic type to a pointer to the derived object itself?

If so, would one of the *_cast<T> functions be more appropriate than the C-style cast?

(Also, if the pointer is to a B object that isn't a base subobject of an object of type D, then its undefined behaviour, right? The implementation has no way to check if the cast is correct, as it does with a dynamic_cast ?)

like image 892
Andrew Tomazos Avatar asked Mar 03 '26 16:03

Andrew Tomazos


1 Answers

Is this program ill-formed or have undefined behaviour?

This program is well formed. You can cast a pointer from a base type to a subtype without any issues.

If so, would one of the *_cast functions be more appropriate than the C-style cast?

Certainly! The default cast to use is static_cast<T>(...). It will avoid casting from/to unrelated types that would incur undefined behaviour.

For example, C-style casts will accept your code even if B and D are unrelated, but refuses the code using static_cast

like image 115
Guillaume Racicot Avatar answered Mar 06 '26 05:03

Guillaume Racicot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!