This is a different question than the other one I’ve posted, I have this piece of code:
class Base
{
public:
Base()
{
};
virtual void Method()
{
cout << "Base Method";
}
};
class Derived : public Base
{
public:
virtual void Method()
{
cout << "Override Method";
}
};
class Derived2 : public Derived
{
public:
Derived2()
{
cout << "Derived2 constructor";
}
void Method()
{
cout << "Override2 Method";
}
};
int main()
{
Base *myPointer = new Derived();
dynamic_cast<Derived2*>(myPointer)->Derived2::Method();
Sleep(700);
delete myPointer;
return 0;
}
If I write
dynamic_cast<Derived2*>(myPointer)->Method();
there’s a failure (dynamic_cast returns NULL and NULL->Method() provokes an exception) and this is what I was expecting, but if I write
dynamic_cast<Derived2*>(myPointer)->Derived2::Method();
the function succeeds without even calling the Derived2 constructor. Method isn’t even a static function, what is going on here?
You triggered undefined behavior by calling a member function on a NULL pointer. If you use
dynamic_cast, you must either check the returned pointer for NULL before dereferencing it or 100% ensure you never cast to a type that is not the type of the object being cast or one of its parents.