title: Avoid duplicated code in inheritance hierarchy in C++
body: <p>I've been having some difficulties with duplicated code in one of my inheritance hierarchy.
  How could I avoid duplicating the code inside function smile()?</p>
  
  <p>Given the fact that the variable <code>_a</code> doesn't exists in the base class I cannot move the function there. Also creating a template function like this <code>template&lt;typename T&gt; void smile(T&amp; a) { a++; }</code> is not really a solution for me. My actual code is a bit more complicated and such a solution would be very messy if not impossible to apply with my current design.</p>
  
  <pre><code>class com
  {
  public:
     com(int x, float y) : _x(2), _y(1.15f)
     {   }
  protected:
     // Common functions go here .We need this base class.
  protected:
     int _x;
     float _y;
  };
  
  class com_int : public com
  {
  public:
     void fill()
     { _a = std::max(_x, (int)_y); }
  protected:
     int _a;
  };
  
  class com_real : public com
  {
  public:
     void fill()
     { _a = std::min((float)_x, _y); }
  protected:
     float _a;
  };
  
  class happy_int : public com_int
  {
  public:
     void smile() { _a ++; } // BAD: Will be duplicated
  };
  
  class happy_float : public com_real
  {
  public:
     void smile() { _a ++; } // BAD: Duplicated code
  }
  
  class sad_int : public com_int
  {
  public:
     frown() { _a --; }
  }
  </code></pre>
  
  <p>Also, does anybody know a good book that teaches how to actually design code in C++ using OOP and template principles? </p>