C++ cannot convert from base A to derived type B v

2019-01-16 14:09发布

I have three classes:

class A {};

class B : virtual public A {};
class C : virtual public A {};

class D: public B, public C {};

Attempting a static cast from A* to B* I get the below error:

cannot convert from base A to derived type B via virtual base A

7条回答
一纸荒年 Trace。
2楼-- · 2019-01-16 14:37

According standard docs,

Section 5.2.9 - 9, for Static Cast,

An rvalue of type “pointer to cv1 B,” where B is a class type, can be converted to an rvalue of type “pointer to cv2 D,” where D is a class derived (clause 10) from B, if a valid standard conversion from “pointer to D” to “pointer to B” exists (4.10), cv2 is the same cv-qualification as, or greater cv-qualification than, cv1, and B is neither a virtual base class of D nor a base class of a virtual base class of D.

Hence, it is not possible and you should use dynamic_cast...

查看更多
登录 后发表回答