This does not compile in C++:
class A
{
};
class B : public A
{
};
...
A *a = new B();
B *b = dynamic_cast<B*>(a);
Because dynamic_cast
can only downcast polymorphic types, so sayeth the Standard.
You can make your class polymoprphic by adding a virtual
destructor to the base class. In fact, you probably should anyway (See Footnote). Else if you try to delete a B
object through an A
pointer, you'll evoke Undefined Behavior.
class A
{
public:
virtual ~A() {};
};
et voila!
There are exceptions to the "rule" about needing a virtual destructor in polymorphic types.
One such exception is when using boost::shared_ptr
as pointed out by Steve Jessop in the comments below. For more information about when you need a virtual destructor, read this Herb Sutter article.