Why do I receive the following error for the following code?
1>C:\\Libs\\boost_1_44\\boost/smart_ptr/shared_ptr.hpp(259): error C2683: \'dynamic_cast\' :
dynamic_cast works ONLY with polymorphic class. And polymorphic class is that which has atleast one virtual function, even be it the destructor.
//polymorphic classes
struct A
{
virtual ~A(); //even virtual destructor makes a class polymorphic!
};
struct B : A
{
void f();
};
//non-polymorphic classes
struct C
{
~C(); //not virtual
};
struct D : C
{
void f(); //not virtual either
};
In the above code, A and B are polymorphic classes, but C and D are not.
A *pA = new B();
B *pB = dynamic_cast(pA); //okay
C *pC = new D();
D *pD = dynamic_cast(pC); //error - not polymorphic class
Note that in dynamic_cast, only the source type need to be polymorphic in order to compile. If the destination isn't polymorphic, then dynamic_cast will return null pointer.
D *pD = dynamic_cast(pA); //okay - source (pA) is polymorphic
if ( pD )
cout << "pD is not null" ;
else
cout << "pD is null";
Output:
pD is null
Online demo: https://web.archive.org/web/20000000000000/http://www.ideone.com/Yesxc