Effective C++ Ed. 3rd: Item 39. Use private inheritance judiciously

A class "is-implemented-in-terms-of" might be achieved by:
  • composition (see prev. item for detail)
  • private inheritance. 
Now, which to use when? Former should be used whenever possible. Private inheritance would be handy when you need to redefine a virtual member function or need to access to protected base class members.
Beside the 2 alternatives mentioned above,
  • we may have a design something like:
class Widget {
private:
  class WidgetTimer: public Timer {
  public:
    virtual void onTick() const;
    ...

  };
   WidgetTimer timer;
  ...

};
In the third alternative's example, we need to redefine onTick() of class Timer.This design is appreciated over private inheritance because 1.the derived classes would not be able to refine onTick(). 2. In case of private inheritance, Widget get compilation dependencies on the definition of class Timer which would force us to #include timer.h Whereas in alternative 3, By defining WidgetTimer class out of the Widget class and placing a pointer to WidgetTimer would require just declaration of WidgetTimer class at the minimum.
prev | next
cheers

No comments:

Post a Comment