Difference between revisions of "Cpp Coding Standards/VIRTUAL/Over"

From Apache OpenOffice Wiki
Jump to: navigation, search
 
 
Line 29: Line 29:
 
   virtual void bar();
 
   virtual void bar();
 
  };
 
  };
 +
[[Category:Coding Standards]]

Latest revision as of 18:00, 14 December 2009

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