FAQ: Why does dynamic_cast only work if a class has at least 1 virtual method?

Filip Frącz picture Filip Frącz · Nov 19, 2010 · Viewed 10.9k times · Source

This does not compile in C++:

class A
{
};

class B : public A
{
};

...

A *a = new B();
B *b = dynamic_cast<B*>(a);

Answer

John Dibling picture John Dibling · Nov 19, 2010

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!

Footnote

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.