After upcasting a derived class’s pointer, a virtual method of the derived class is still called, which seems to me wrong, as slicing should have happened.
Could you please comment what’s wrong with this code?
class Base
{
public:
virtual void Hello() { cout << "Hello Base" << endl; }
};
class Derived: public Base
{
public:
void Hello() { cout << "Hello Derived" << endl; }
};
int main()
{
Derived* der = new Derived;
Base* base = dynamic_cast<Base*> (der);
if (base) base->Hello();
}
output: Hello Derived
Slicing did not happen because you didn’t work with any values of
Base, just pointers to it.This would cause slicing:
But if you want to call a function and suppress dynamic dispatch, you can just do this:
The function to call is specified statically. This works with
dertoo, of course, avoiding the middle-man.Your
dynamic_castis not needed here. You can implicitly upcast, because this is trivially verifiable at compile-time. You can usestatic_castto downcast, but it’s up to you to make sure this is actually correct;dynamic_castis just a checked version of that.