The reason dynamic_cast does not work with non-polymorphic types

With classes Band a derived class D:

class B {
    int b;
};


class D : public B {
    int d;
};


D* d = new D();
B* b = dynamic_cast<B*>(d);

The above will work fine, this is a simple enhancement. We are sure that no matter what it points to B, there is a Bclass (sub-) object in it.

However

B* b = new D();
D* d = dynamic_cast<D*>(b);

will not compile even if it Bpoints to a valid instance D- mdash, because the base class is not polymorphic. Thus, adding only one empty virtual method will solve the problem.

: ++ , ? , , this, , " " - , ). , dynamic_cast, , - ?

+4
2

dynamic_cast - , . , : dynamic_cast.

dynamic_cast - , . " , " ++, C , .. . , , , .

+4

dynamic_cast , RTTI ( dynamic_cast RTTI - - , ), , . - , ( 0 ).

+3

All Articles