Tuesday, March 1, 2016

Keep virtual!

I've just made some code changes to code in which rather consistently this is happening:

class Base
   virtual void func();

class Derived : public Base
    void func();

What is the consequence of not keeping the virtual keyword in Derived? Well, for the compiler, nothing. It's OK. The derived class' func() will be virtual no matter whether you declare it as such.

But code is not only for the C++ compiler. I prefer to keep the virtual keyword in Derived, By repeating the virtual keyword you say something to the reader of the class' interface: hey, take a look at the base class, I'm implementing (or overruling) an existing interface here. Note that C++11 has 'override' to help you with this.

There's also potential human suffering. If Derived is later derived from, then using func() in the constructor is a dangerous thing (virtual functions and constructors - scary combo). Hopefully the creater of that new class will take a peek at base.h early to discover this before having to debug this away ....

No comments:

Post a Comment