In C ++, does this Undefined Behavior exist if an object of a base class is created as a base object and subsequently omitted from a derived object?
Of course, I would suggest that this definitely should be Undefined behavior, because an object of the Derived class can have member variables that are not in the base class. Thus, these variables would not really exist if the class instance was created as a base object, which means that access to them through the Derived class pointer should cause Undefined Behavior.
But what if the Derived class simply provides additional member functions but does not contain any additional member data? For instance:
class Base { public: int x; }; class Derived : public Base { public: void foo(); }; int main() { Base b; Derived* d = static_cast<Derived*>(&b); d->foo();
Does this program cause Undefined behavior?
source share