What is the reason of implicit virtual-ness propagation?

情到浓时终转凉″ 提交于 2019-12-05 05:56:20

The answer as to why a particular feature exists (or doesn't) is usually rather difficult, as it becomes a matter of guessing and opinions. However, the simple answer could be the principle of least astonishment. Coming up with a scheme that makes sense and works reliably and predictably would be difficult.

What would "devirtualizing" a function even mean? If, at runtime, you're calling a "devirtualized" function on an object, would it use the static type of the pointer instead? If the static type has a virtual function but the runtime type doesn't, what happens?

#include <iostream>

struct A     {  virtual void f() const { std::cout << "A"; }  };
struct B : A {          void f() const { std::cout << "B"; }  };
struct C : B {  virtual void f() const { std::cout << "C"; }  };
struct D : C {          void f() const { std::cout << "D"; }  };

void f(const A& o) { o.f(); }

int main()
{
                // "devirtualized"     real C++

    f(A{});     // "A"                 "A"
    f(B{});     // "A" or "B"?         "B"
    f(C{});     // "C"?                "C"
    f(D{});     // oh god              "D"
}

There's also the fact that for the vast majority of designs, a virtual function has to stay virtual in the whole hierarchy. Requiring virtual on all of them would introduce all sorts of bugs that would be very hard to diagnose. C++ usually tries to stay away from features that require discipline to get right.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!