On May 10, 8:36 pm, Keith Halligan <keith.halli...@gmail.comwrote:
I have read that if a base class declares a function "fun" as virtual
all derived classes inherits this virtual function and does not need to
use the keyword "virtual" in their declarations.
Yes thats true, it's just a lot of people add it in, so that a new
class was derived from Circle then we could specialise it's
implementation of the Intersect function.
As far as the language is concerned, there is absolutely no
difference whether the virtual is present in Circle or not. If
a function is virtual in a base class, it is virtual in all
derived classes, always. There's no way you can turn virtuality
off, once it's established.
In a similar way a lot of people create Base class destructors as
virtual even though it's only explicitly required in the derived
classes.
It's just an example of safe coding.
No. If you delete an object through a Base*, and the actual
type of the object is not B, it is undefined behavior if the
destructor is not virtual. Although the names of the
destructors in derived classes may not look the same, all
destructors are treated as the "same function", with regards to
virtuality. Virtual on the destructor of the base class implies
that all destructors of all derived classes are virtual as well.
To answer the original question: as far as the compiler is
concerned, the only time you need virtual in a derived class is
when that class introduces new virtual functions. Human beings,
however, read code differently than the compiler. When the
compiler sees the derived class definition, it has already read
the base class definition, and has all of the information in its
symbol table. When a human reads the code, he often has not
seen the base class definition, and doesn't really want to have
to go back to it to know what is going on. So every coding
guideline I've seen requires the use of virtual in the derived
class as well.
--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34