With classes B
and derived class D
:
class B {
int b;
};
class D : public B {
int d;
};
D* d = new D();
B* b = dynamic_cast<B*>(d);
the above will work fine—it's a simple upcasting. We're sure that whatever b
is pointing at has the B
class (sub-)object in it.
However,
B* b = new D();
D* d = dynamic_cast<D*>(b);
won't compile even though b
points to a valid D
instance—because the base class is not polymorphic. So adding just one, empty virtual method would solve the problem.
The important question is why C++ requires the source type to be polymorphic? The only explanation I've found is this, but it merely states 'because that's how it's implemented internally' - at least in my eyes). People who designed dynamic_cast
probably had some other reasons in mind - what were those?
virtual
destructor in the base class. – πάντα ῥεῖ