Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The reason why dynamic_cast doesn't work with non-polymorphic types

With classes B and 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—it's a simple upcasting. We're sure that whatever b is pointing at has the B class (sub-)object in it.

However,

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

won't compile even though b points to a valid D instance—because the base class is not polymorphic. So adding just one, empty virtual method would solve the problem.

The important question is why C++ requires the source type to be polymorphic? The only explanation I've found is this, but it merely states 'because that's how it's implemented internally' - at least in my eyes). People who designed dynamic_cast probably had some other reasons in mind - what were those?

like image 939
user5539357 Avatar asked Mar 01 '16 17:03

user5539357


1 Answers

Because there is no way to implement dynamic_cast without some type information stored in the object for run-time use. And there are only two features of the language which need a run-time information on the object's type: virtual functions, and dynamic_cast.

If it was possible to use dynamic_cast to downcast non-polymorphic types, compliers would have to store run-time type information in every class type. This would go directly against the "only pay for what you use" philosophy of C++, and it would utterly break its compatibility with C and many external interfaces, hardware etc. There would be no standard-layout class types, basically. Or, alternatively, no class types where you could have full control of their layout.

like image 147
Angew is no longer proud of SO Avatar answered Sep 18 '22 14:09

Angew is no longer proud of SO