Effective C++ Ed. 3rd: Item 37. Never redefine a function's inherited default parameter value

Never redefine an inherited default parameter value, because these are statically bound unlike the virtual functions ( the only functions which should be overridding).
The following NVI technique is one of the alternatives if you want to redefine an inherited default parameter value:
class Shape {
public:
  enum ShapeColor { Red, Green, Blue };

  void draw(ShapeColor color = Red) const           // now non-virtual
  {
    doDraw(color);                                  // calls a virtual
  }

  ...

private:
  virtual void doDraw(ShapeColor color) const = 0;  // the actual work is
};                                                  // done in this func

class Rectangle: public Shape {
public:

  ...

private:
  virtual void doDraw(ShapeColor color) const;       // note lack of a
  ...                                                // default param val.
};

prev | next
Cheers

No comments:

Post a Comment