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

后端 未结 8 2141
庸人自扰
庸人自扰 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条回答
  •  -上瘾入骨i
    2020-12-11 01:44

    I'm wondering why does a struct\class in C++ has to have a virtual method in order to be polymorphic?

    Because that is what polymorphic class means.

    In C++, runtime polymorphism is achieved through virtual functions. A base class declares some virtual functions which the many derived classes implement, and the clients use pointers (or references) of static type of base class, and can make them point to objects of derived classes (often different derived classes), and then later on, call the implementation of derived classes through the base pointers. That is how runtime polymorphism is achieved. And since the central role is played by the functions being virtual, which enables runtime polymorphism, that is why classes having virtual functions is called polymorphic class.

提交回复
热议问题