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