title: Why is copy constructor not being called in this code
body: <p>So why is Copy constructor not being invoked in "<strong>const Integer operator+(const Integer &amp;rv)</strong>" function. Is it because of RVO. <strong>If Yes what do I need to do to prevent it?</strong></p>
  
  <pre><code>#include &lt;iostream&gt;
  
  using namespace std;
  
  class Integer {
      int i;
  
  public:
      Integer(int ii = 0) : i(ii) {
          cout &lt;&lt; "Integer()" &lt;&lt; endl;
      }
  
      Integer(const Integer &amp;I) {
          cout &lt;&lt; "Integer(const Integer &amp;)" &lt;&lt; endl;
      }
  
      ~Integer() {
          cout &lt;&lt; "~Integer()" &lt;&lt; endl;
      }
  
      const Integer operator+(const Integer &amp;rv) const {
          cout &lt;&lt; "operator+" &lt;&lt; endl;
          Integer I(i + rv.i);
          I.print();
          return I;
      }
  
      Integer &amp;operator+=(const Integer &amp;rv) {
          cout &lt;&lt; "operator+=" &lt;&lt; endl;
          i + rv.i;
          return *this;
      }
  
      void print() {
          cout &lt;&lt; "i: " &lt;&lt; i &lt;&lt; endl;
      }
  };
  
  int main() {
      cout &lt;&lt; "built-in tpes:" &lt;&lt; endl;
      int i = 1, j = 2, k = 3;
      k += i + j;
      cout &lt;&lt; "user-defined types:" &lt;&lt; endl;
      Integer ii(1), jj(2), kk(3);
      kk += ii + jj;
  
  }
  </code></pre>
  
  <p>I do get an error If I'll comment out copy constructor. I'm expecting copy constructor to be called when operator+ returns. Following is the output of the program</p>
  
  <pre><code>built-in tpes:
  user-defined types:
  Integer()
  Integer()
  Integer()
  operator+
  Integer()
  i: 3 // EXPECTING Copy Constructor to be called after this
  operator+=
  ~Integer()
  ~Integer()
  ~Integer()
  ~Integer()
  </code></pre>