0

I wrote this program,I'm trying to make sense of the copy constructor,

#include <iostream>

using namespace std;

class MyClass {

public:
  int a;
  MyClass() {}

  MyClass(const MyClass &c) {
    cout << "Copy constructor\n";
    a = c.a;
  }
};

MyClass fun() {
  MyClass m;
  m.a = 10;
  return m;
}

int main() {
  //   MyClass temp = fun();
  MyClass tmp1;
  tmp1.a = 10;
  MyClass tmp2 = tmp1;
  MyClass tmp3 = fun();
  cout << "tmp1.a = " << tmp1.a << endl;
  cout << "tmp2.a = " << tmp2.a << endl;
  cout << "tmp3.a = " << tmp3.a << endl;
  return 0;
}

And the output is like this,

Copy constructor
tmp1.a = 10
tmp2.a = 10
tmp3.a = 10

Basically, the copy constructor is only called when I do MyClass tmp2 = tmp1;, why doesn't it get called when doing MyClass tmp3 = fun();?I thought copy constructor will be called for that too since It copies values returned by fun() to tmp3.Why isn't this working?

Nethrenial.
  • 146
  • 1
  • 10

0 Answers0