Cpp Coding Standards/VIRTUAL/Over

From Apache OpenOffice Wiki
< Cpp Coding Standards‎ | VIRTUAL
Revision as of 11:48, 13 April 2007 by Np (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Overrides (Over)

Details

If different overrides of a virtual function have different default values, the behaviour is unpredictable. This is forbidden by the C++ standard. It would violate the Liskov Substitution Principle as well.

Overrides of virtual functions are virtual by default, because the language enforces this. But for maintainers of derived classes it is painful, if they cannot see immediately, if a function is virutal, but have to refer to its base classes. Therefore write "virtual" in front of every overriding function as well.

Example

Given the base class:

class X 
{ // ...
  virtual void foo(int param = 5);
  virtual void bar();
};

this would be undesirable:

class Y : public X 
{ // ...
  virtual void foo( int param = 7);  // Unpredictable behaviour
  void         bar();                // Maintainers nightmare: Might this be a virtual function?
};

but this right:

class Y : public X 
{ // ...
  virtual void foo(int param = 5);
  virtual void bar();
};
Personal tools