title: C++ : Implementing copy constructor and copy assignment operator
body: <p>After reading about copy constructors and copy assignment operators in C++, I tried to create a simple example. Though the below snippet apparently works, I am not sure whether I am implementing the copy constructor and copy assignment operator the right way. Could you please point out if there are any mistakes/improvements or a better example to understand the relevant concepts.</p>
  
  <pre><code>class Foobase
  {
      int bInt;
  
  public:
      Foobase() {}
  
      Foobase(int b) { bInt = b;}
  
      int GetValue() { return bInt;}
  
      int SetValue(const int&amp; val) { bInt = val; }
  };
  
  
  class Foobar
  {
      int var;    
      Foobase *base;      
  
  public:
      Foobar(){}
  
      Foobar(int v)
      {
          var = v;        
          base = new Foobase(v * -1);
  
      }
  
      //Copy constructor
      Foobar(const Foobar&amp; foo)
      {       
          var = foo.var;
          base = new Foobase(foo.GetBaseValue());
      }
  
      //Copy assignemnt operator
      Foobar&amp; operator= (const Foobar&amp; other)
      {
          if (this != &amp;other) // prevent self-assignment
          {
              var = other.var;
              base = new Foobase(other.GetBaseValue());
  
          }
          return *this;
      }
  
      ~Foobar()
      {
          delete base;
      }
  
      void SetValue(int val)
      {
          var = val;
      }
  
      void SetBaseValue(const int&amp; val)
      {
          base-&gt;SetValue(val);
      }
  
      int GetBaseValue() const
      {
          return(base-&gt;GetValue());
      }
  
      void Print()
      {
          cout&lt;&lt;"Foobar Value: "&lt;&lt;var&lt;&lt;endl;
          cout&lt;&lt;"Foobase Value: "&lt;&lt;base-&gt;GetValue()&lt;&lt;endl;
  
      }   
  
  };
  
  int main()
  {
      Foobar f(10);       
      Foobar g(f);  //calls copy constructor
      Foobar h = f; //calls copy constructor
  
      Foobar i;
      i = f;
  
      f.SetBaseValue(12);
      f.SetValue(2);    
  
      Foobar j = f = z; //copy constructor for j but assignment operator for f
  
      z.SetBaseValue(777);
      z.SetValue(77);
  
      return 1;
  }
  </code></pre>