0
102 Mar 21, 2011 at 11:16

Hi all,

C++ allows you to omit the ‘virtual’ keyword from methods in derived classes, if it has been declared virtual in the base class. As far as I’m aware, this has no effect whatsoever on the semantics.

So in order to have a consistent style I’m trying to determine whether it should always be omitted, always be written, or if it depends on the situation?

It seems valuable to me to not have to always check the base class, but at the same time it’s easy to forget to write the keyword so there’s no guarantee that if a method is not explicitly virtual, it really isn’t virtual. I also wonder whether there’s any realistic scenario where you’d want the base method to no longer be virtual and no longer have virtual derived methods either (imagine getting a new header file from a third party)…

Anyone got experience with the caveats?

Thanks,

Nicolas

#### 4 Replies

0
101 Mar 21, 2011 at 11:40

I would opt to always write virtual, for sake of documentation.

Changing a base class method to nonvirtual will probably silently break anyway, whether you have made the method in the derived class virtual or not. However, if you had specified ‘virtual’, breakage is limited to the base class (if the derived class calls the method, any derived class of the derived class will still catch it).

But what I usually do in such breaking interface changes, is create a new method, and deprecate the old one by using a different return type.

// before the change
class Base
{
public:
virtual void Foo() { /* ... */ }
};

class Derived : public Base
{
public:
virtual void Foo() { /* ... */ }
};

/////////////////////////////////////////////////////////////////
// AFTER changing Base

struct method_is_deprecated;

class Base
{
public:
void NewNonVirtualFoo() { /* ... */ }

private:
method_is_deprecated Foo();
};

class Derived : public Base
{
public:
virtual void Foo() { /* ... */ } // compile error, incompatible return types
};

0
101 Mar 21, 2011 at 12:06

Please use ‘virtual’ in derived classes, for clarity. :)

Stack-Overflow:

0
176 Mar 21, 2011 at 13:34

As others have said, although for my own personal preference I usually do not include the virtual keyword in derived classes where I don’t want a particular method touched any further, but the class itself can still be expanded on. Otherwise I follow any coding practices recommended by the business, if they have any.

It’s rare that I ever need to modify the inheritable members of a base class. If I do, first I slap myself for bad design, secondly I will check with the derived classes to ensure correctness, especially if that code comes from a 3rd party. A code review of the affected areas would be an absolute must.

0
102 Mar 21, 2011 at 21:40