Why is the “virtuality” of methods implicitly propagated in C++?

前端 未结 4 1068
闹比i
闹比i 2021-01-04 08:13

What is the reason for removing the ability to stop the propagation of methods virtuality?

Let me be clearer: In C++, whether you write \"virtual void foo()\" or \"v

4条回答
  •  滥情空心
    2021-01-04 08:26

    I think the reason is that it would be really confusing to remove virtuality partway through an inheritance structure (I have an example of the complexity below).

    However if your concern is the micro-optimization of removing a few virtual calls then I wouldn't worry. As long as you inline the virtual child method's code, AND your iterator is passed around by value and not reference, a good optimizing compiler will already be able to see the dynamic type at compile time and inline the whole thing for you in spite of it being a virtual method!

    But for completeness, consider the following in a language where you can de-virtualize:

    class A
    {
    public:
        virtual void Foo() { }
    };
    
    class B : public A
    {
    public:
        void Foo() { } // De-virtualize
    };
    
    class C: public B
    {
    public:
        void Foo() { } // not virtual
    };
    
    void F1(B* obj)
    {
        obj->Foo();
        static_cast(obj)->Foo();
    }
    
    C test_obj;
    F1(test_obj);   // Which two methods are called here?
    

    You could make rules for exactly which methods would get called but the obvious choice will vary from person-to-person. It's far simpler to just propagate virtualness of a method.

提交回复
热议问题