C++ “virtual” keyword for functions in derived classes. Is it necessary?

后端 未结 9 1415
遇见更好的自我
遇见更好的自我 2020-11-22 15:17

With the struct definition given below...

struct A {
    virtual void hello() = 0;
};

Approach #1:

struct B : public A {
           


        
相关标签:
9条回答
  • 2020-11-22 15:28

    They are exactly the same. There is no difference between them other than that the first approach requires more typing and is potentially clearer.

    0 讨论(0)
  • 2020-11-22 15:33

    The virtual keyword should be added to functions of a base class to make them overridable. In your example, struct A is the base class. virtual means nothing for using those functions in a derived class. However, it you want your derived class to also be a base class itself, and you want that function to be overridable, then you would have to put the virtual there.

    struct B : public A {
        virtual void hello() { ... }
    };
    
    struct C : public B {
        void hello() { ... }
    };
    

    Here C inherits from B, so B is not the base class (it is also a derived class), and C is the derived class. The inheritance diagram looks like this:

    A
    ^
    |
    B
    ^
    |
    C
    

    So you should put the virtual in front of functions inside of potential base classes which may have children. virtual allows your children to override your functions. There is nothing wrong with putting the virtual in front of functions inside of the derived classes, but it is not required. It is recommended though, because if someone would want to inherit from your derived class, they would not be pleased that the method overriding doesn't work as expected.

    So put virtual in front of functions in all classes involved in inheritance, unless you know for sure that the class will not have any children who would need to override the functions of the base class. It is good practice.

    0 讨论(0)
  • 2020-11-22 15:34

    There's a considerable difference when you have templates and start taking base class(es) as template parameter(s):

    struct None {};
    
    template<typename... Interfaces>
    struct B : public Interfaces
    {
        void hello() { ... }
    };
    
    struct A {
        virtual void hello() = 0;
    };
    
    template<typename... Interfaces>
    void t_hello(const B<Interfaces...>& b) // different code generated for each set of interfaces (a vtable-based clever compiler might reduce this to 2); both t_hello and b.hello() might be inlined properly
    {
        b.hello();   // indirect, non-virtual call
    }
    
    void hello(const A& a)
    {
        a.hello();   // Indirect virtual call, inlining is impossible in general
    }
    
    int main()
    {
        B<None>  b;         // Ok, no vtable generated, empty base class optimization works, sizeof(b) == 1 usually
        B<None>* pb = &b;
        B<None>& rb = b;
    
        b.hello();          // direct call
        pb->hello();        // pb-relative non-virtual call (1 redirection)
        rb->hello();        // non-virtual call (1 redirection unless optimized out)
        t_hello(b);         // works as expected, one redirection
        // hello(b);        // compile-time error
    
    
        B<A>     ba;        // Ok, vtable generated, sizeof(b) >= sizeof(void*)
        B<None>* pba = &ba;
        B<None>& rba = ba;
    
        ba.hello();         // still can be a direct call, exact type of ba is deducible
        pba->hello();       // pba-relative virtual call (usually 3 redirections)
        rba->hello();       // rba-relative virtual call (usually 3 redirections unless optimized out to 2)
        //t_hello(b);       // compile-time error (unless you add support for const A& in t_hello as well)
        hello(ba);
    }
    

    The fun part of it is that you can now define interface and non-interface functions later to defining classes. That is useful for interworking interfaces between libraries (don't rely on this as a standard design process of a single library). It costs you nothing to allow this for all of your classes - you might even typedef B to something if you'd like.

    Note that, if you do this, you might want to declare copy / move constructors as templates, too: allowing to construct from different interfaces allows you to 'cast' between different B<> types.

    It's questionable whether you should add support for const A& in t_hello(). The usual reason for this rewrite is to move away from inheritance-based specialization to template-based one, mostly for performance reasons. If you continue to support the old interface, you can hardly detect (or deter from) old usage.

    0 讨论(0)
  • 2020-11-22 15:36

    Adding the "virtual" keyword is good practice as it improves readability , but it is not necessary. Functions declared virtual in the base class, and having the same signature in the derived classes are considered "virtual" by default.

    0 讨论(0)
  • 2020-11-22 15:37

    I will certainly include the Virtual keyword for the child class, because

    • i. Readability.
    • ii. This child class my be derived further down, you don't want the constructor of the further derived class to call this virtual function.
    0 讨论(0)
  • 2020-11-22 15:43

    The 'virtualness' of a function is propagated implicitly, however at least one compiler I use will generate a warning if the virtual keyword is not used explicitly, so you may want to use it if only to keep the compiler quiet.

    From a purely stylistic point-of-view, including the virtual keyword clearly 'advertises' the fact to the user that the function is virtual. This will be important to anyone further sub-classing B without having to check A's definition. For deep class hierarchies, this becomes especially important.

    0 讨论(0)
提交回复
热议问题