Garmaine Staff asked 4 months ago

Is the following legit in C++? The derived class is allocating base class and cast it to derived. Obviously if derived (C) has members, anyone accessing members via the returned pointer would fail. But even without members in derive – is this legit? UB ?

struct B { int a; };
struct C : B { 
   static C* get() {
       return static_cast<C*>(new B);
   }
   enum { X, Y,};
};
int main(){
   C* c = C::get();
   return c->X;
}