[bind10-dev] usage of "virtual" declarations in derived classes
JINMEI Tatuya / 神明達哉
jinmei at isc.org
Wed Jul 21 08:34:06 UTC 2010
In his review on trac #221, Evan said:
: Seeing that the methods in XfroutClient had been changed from
: non-virtual to virtual confused me for a bit; I thought there must be
: another derived class somewhere that extended XfroutClient them, and
: was wondering if I was missing part of the code. I'd appreciate a
: comment explaining why they're virtual.
https://bind10.isc.org/ticket/221#comment:25
I realized this basically comes from difference on what we would
expect in a "virtual" declaration in a derived class, and thought it's
better to discuss in a wider place.
In general I use virtual in a derived class when that member function
(polymorphically) overrides the same name of function of the base
class:
class Base {
public:
virtual void func() = 0;
};
class Derived : public Base {
public:
virtual void func(); // overrides Base.fun().
};
The second virtual is redundant, but I normally add it explicitly to
make the intent of overriding clearer (and also as suggested in one of
my usual references, "C++ Coding Standards").
On the other hand, Evan seems to expect, when he sees the second
definition, that this second virtual indicates there should be another
derived class inherited from class Derived. (And, if I remember a
previous jabber chat correctly some others interpret it that way).
I never use virtual to indicate "further inheritance". I'd generally
even avoid using inheritance from a non base class such as "Derived"
above in the first place.
Note that we do not *have to* add virtual if we want to allow further
inheritance and let the grandchild class override its func():
class MoreDerived : public Derived {
public:
void func(); // this will work equally with or without virtual in "Derived".
};
In this case the style I'm using is mostly a not so strong preference,
so if it makes the code look awkward to other developers, I'd rather
stop using it than adding comments on "why I use virtual here" in
every use case of this style of virtual. On the other hand, if this
style makes sense, I think we should consistently use it throughout
our code and add it as a general coding guideline on wiki, again,
rather than making comments on it in every case where it's used.
Opinions?
---
JINMEI, Tatuya
Internet Systems Consortium, Inc.
More information about the bind10-dev
mailing list