C++: Why does a struct\class need a virtual method in order to be polymorphic?

后端 未结 8 2143
庸人自扰
庸人自扰 2020-12-11 01:42

Following this question, I\'m wondering why a struct\\class in C++ has to have a virtual method in order to be polymorphic.

Forcing a virtual destructor makes sense,

8条回答
  •  被撕碎了的回忆
    2020-12-11 01:53

    Because it is defined as such in the standard.

    From 10.3/1 [class.virtual]

    Virtual functions support dynamic binding and object-oriented programming. A class that declares or inherits a virtual function is called a polymorphic class.

    It makes sense that if you use inheritance, then you have at least one virtual method. If you don't have any virtual method, then you could use composition instead.

提交回复
热议问题