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

后端 未结 8 2131
庸人自扰
庸人自扰 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:58

    Forcing a virtual destructor makes sense

    Exactly. To destruct a virtual class manually (via delete) through its base class you need a virtual destructor. (Now, as I’ve been reminded in the comments, this isn’t usually needed: rather than use manual memory management, one would rely on modern smart pointers which also work correctly with non-virtual destructors.)

    So any class which acts as a polymorphic base class usually needs either a virtual destructor or virtual functions anyway.

    And since having runtime polymorphism adds an overhead (the class needs to store an additional pointer to its virtual method table), the default is not to add it, unless necessary anyway: C++’ design philosophy is “you only pay for what you need”. Making every class have a virtual method table would run afoul of this principle.

提交回复
热议问题