C++ Style: Prefixing virtual keyword to overridden methods

后端 未结 6 636
名媛妹妹
名媛妹妹 2020-12-09 03:15

I\'ve been having a discussion with my coworkers as to whether to prefix overridden methods with the virtual keyword, or only at the originating base class.

I tend t

6条回答
  •  醉话见心
    2020-12-09 03:40

    A function once a virtual always a virtual.

    So in any event if the virtual keyword is not used in the subsequent classes, it does not prevent the function/method from being 'virtual' i.e. be overridden. So one of the projects that I worked-in, had the following guideline which I somewhat liked :

    • If the function/method is supposed to be overridden always use the 'virtual' keyword. This is especially true when used in interface / base classes.
    • If the derived class is supposed to be sub-classed further explicity state the 'virtual' keyword for every function/method that can be overridden. C++11 use the 'override' keyword
    • If the function/method in the derived class is not supposed to be sub-classed again, then the keyword 'virtual' is to be commented indicating that the function/method was overridden but there are no further classes that override it again. This ofcourse does not prevent someone from overriding in the derived class unless the class is made final (non-derivable), but it indicates that the method is not supposed to be overridden. Ex: /*virtual*/ void guiFocusEvent(); C++11, use the 'final' keyword along with the 'override' Ex: void guiFocusEvent() override final;

提交回复
热议问题