Can't downcast because class is not polymorphic?

后端 未结 5 1818
时光取名叫无心
时光取名叫无心 2020-12-04 23:32

Is it possible to have inheritance with no virtual methods? The compiler is saying that the following code is not polymorphic.

Example:

Class A(){
           


        
5条回答
  •  北海茫月
    2020-12-05 00:07

    A a;
    B *b = dynamic_cast(a)
    

    Here a is an object and b is a pointer.

    Actually, upcasting and downcasting are both allowed in C++. But when using downcasting, 2 things should be pay attention to: 1 The superclass should has at least one virtual method. 2 Since superclass is "smaller" than subclass, one should use memory object carefully.

提交回复
热议问题