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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…