4

For example:

class Animal
{
    virtual void dummy() {};         //LINE1
}

class Cat : public Animal
{

}

Animal* a = new Cat();
if (Cat* c = dynamic_cast<Cat*> (a))  //LINE2
{
     //Do something.
}

If I remove LINE1 from the Animal class (i.e. Animal class does not contain virtual members), LINE2 will not work.

John
  • 193
  • 2
  • 14

2 Answers2

9

dynamic_cast can cast to the same class or base class without virtual members. But for downcasting or casting to void* (which yields a pointer to the most derived class object) dynamic_cast requires a polymorphic class, per C++11 §5.2.7/6:

“Otherwise, v shall be a pointer to or an lvalue of a polymorphic type”

where v is the argument you supply.

A polymorphic class is one that has one or more virtual member functions, §10.3/1:

“A class that declares or inherits a virtual function is called a polymorphic class.”

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
8

Yes it does, as per the standard, dynamic_cast can only downcast polymorphic types (i.e. a type with at least one virtual function)

quantdev
  • 23,517
  • 5
  • 55
  • 88