Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

This does not compile in C++:

class A { };  class B : public A { };  ...  A *a = new B(); B *b = dynamic_cast<B*>(a); 
like image 934
Filip Frącz Avatar asked Nov 19 '10 16:11

Filip Frącz


People also ask

Why do we use dynamic_cast?

The primary purpose for the dynamic_cast operator is to perform type-safe downcasts. A downcast is the conversion of a pointer or reference to a class A to a pointer or reference to a class B , where class A is a base class of B .

Why does dynamic_cast return null?

If the cast is successful, dynamic_cast returns a value of type new-type. If the cast fails and new-type is a pointer type, it returns a null pointer of that type. If the cast fails and new-type is a reference type, it throws an exception that matches a handler of type std::bad_cast.

Can dynamic_cast throw exception?

dynamic_cast will no longer throw an exception when type-id is an interior pointer to a value type, with the cast failing at runtime. The cast will now return the 0 pointer value instead of throwing.

Does dynamic_cast use RTTI?

For example, dynamic_cast uses RTTI and the following program fails with the error “cannot dynamic_cast `b' (of type `class B*') to type `class D*' (source type is not polymorphic) ” because there is no virtual function in the base class B.


1 Answers

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.

like image 139
John Dibling Avatar answered Sep 25 '22 12:09

John Dibling