In C++, is it Undefined Behavior if a Base class object is instantiated as a base object, and subsequently downcast to a derived object?
Of course, I would assume it definitely must be undefined behavior, because the Derived class object might have member variables which the base class doesn't. So these variables wouldn't actually exist if the class was instantiated as a base object, which means that accessing them through a Derived class pointer would have to cause Undefined Behavior.
But, what if the Derived class simply provides extra member functions, but doesn't include any further member data? For example:
class Base
{
public:
int x;
};
class Derived : public Base
{
public:
void foo();
};
int main()
{
Base b;
Derived* d = static_cast<Derived*>(&b);
d->foo(); // <--- Is this undefined behavior?
}
Does this program cause undefined behavior?
See Question&Answers more detail:os