C++ Style: Prefixing virtual keyword to overridden methods

后端 未结 6 635
名媛妹妹
名媛妹妹 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:36

    Note: My answer regards C++03 which some of us are still stuck with. C++11 has the override and final keywords as @JustinTime suggests in the comments which should probably be used instead of the following suggestion.

    There are plenty of answers already and two contrary opinions that stand out the most. I want to combine what @280Z28 mentioned in his answer with @StevenSudit's opinion and @Abhay's style guidelines.

    I disagree with @280Z28 and wouldn't use Microsoft's language extensions unless you are certain that you will only ever use that code on Windows.

    But I do like the keywords. So why not just use a #define-d keyword addition for clarity?

    #define OVERRIDE
    #define SEALED
    

    or

    #define OVERRIDE virtual
    #define SEALED virtual
    

    The difference being your decision on what you want to happen in the case you outline in your 3rd point.

    3 - If, through some error, the virtual were removed from IFoo, all children will still function (CFooSpecialization::DoBar would still override CFooBase::DoBar, rather than simply hiding it).

    Though I would argue that it is a programming error so there is no "fix" and you probably shouldn't even bother mitigating it but should ensure it crashes or notifies the programmer in some other way (though I can't think of one right now).

    Should you chose the first option and don't like adding #define's then you can just use comments like:

    /* override */
    /* sealed */
    

    And that should do the job for all cases where you want clarity, because I don't consider the word virtual to be clear enough for what you want it to do.

提交回复
热议问题