-1
class A
{
};

class B:public A
{
};
int main()
{
    A a;
    B b;
    A *ap = &b;
    B *bp = dynamic_cast<B*>(ap);
    if(bp!= NULL)
       cout<<"Pass"<<endl;
    else
       cout<<"Fail"<<endl;
    return 0;
}

Why should class A be virtual if you want to do a dynamic cast?

arrowd
  • 33,231
  • 8
  • 79
  • 110
ranganath111
  • 457
  • 2
  • 7
  • 17

3 Answers3

7

dynamic_cast works differently from static_cast. The results of a static_cast are always a pointer. However, if the cast is incorrect (to a type that the given pointer wasn't originally), then the result of the cast is undefined; the pointer is not necessarily valid. Thus, there is some degree of uncertainty when casting to derived classes with static_cast; there is no mechanism to prevent you from casting to the wrong things.

dynamic_cast will return either a valid pointer if the cast is correct, or a null pointer if it is incorrect. Thus, the results are well-defined in all cases. In order to do this, dynamic_cast must be dynamic. This means that it has to do runtime checks on the pointer to see if the type being cast to is a legal cast operation.

C++ forbids casts for non-virtual types due to the "pay for what you use" principle: a type that doesn't have virtual functions is generally not a type that you're passing around by its base classes. Inheritance without virtuals is primarily about using the existing implementation, not about specializing functions. Even something as simple as a virtual destructor is sufficient.

The machinery needed to do dynamic_cast is non-zero. So, under the "pay for what you use" principle, only those classes where it would be useful pay for them. IE: those classes which are virtual.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
1

The output will be something along the lines:

Error xxxx: invalid parameter to dynamic_cast. Class is of non-polymorphic type.

The classes need to be polymorphic because that's the specification for dynamic_cast. Internally, dynamic_cast checks virtual table pointers, but that's an implementation detail.

You can use static_cast in this case.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
0

virtual is the key of polymorphysm. A virtual function means it is "overriddenable" by a derived class, otherwise there is no polymorphysm between the classes, there is just inheritance. If the classes are not polymorphic, the dynamic_cast cannot be used.

thedarkside ofthemoon
  • 2,251
  • 6
  • 31
  • 48