C++ Style: Prefixing virtual keyword to overridden methods
c++, coding-style, methods, virtual-functions
Solution
I completely agree with your rationale. It's a good reminder that the method will have dynamic dispatch semantics when called. The "that method isn't virtual" argument that you co-worker is using is completely bogus. He's mixed up the concepts of virtual and pure-virtual.
Problem
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 to prefix all virtual methods (that is, methods involving a vtable lookup) with the virtual keyword. My rationale is threefold: Given that C++ lacks an override keyword, the presence of the virtual keyword at least notifies you that the method involves a lookup and could theoretically be overridden by further specializations, or could be called through a pointer to a higher base class. Consistently using this style means that, when you see a method (at least within our code) without the virtual keyword, you can initially assume that it is neither derived from a base nor specialized in subclass. 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). The argument against the practice, as I understood it, was, "But that method isn't virtual" (which I believe is invalid, and borne from a misunderstanding of virtuality), and "When I see the virtual keyword, I expect that means someone is deriving from it, and go searching for them." The hypothetical classes may be spread across several files, and there are several specializations. ``` class IFoo { public: virtual void DoBar() = 0; void DoBaz(); }; class CFooBase : public IFoo { public: virtual void DoBar(); // Default implementation void DoZap(); }; class CFooSpecialization : public CFooBase { public: virtual void DoBar(); // Specialized implementation }; ``` Stylistically, would you remove the virtual keyword from the two derived classes? If so, why? What are Stack Overflow's thoughts here?