Consider Below example:
#include <iostream> using namespace std; class Test{ public: int a; Test(int a=0):a(a){ cout << "Ctor " << a << endl;} Test(const Test& A):a(A.a){ cout << "Cpy Ctor " << a << endl;} Test operator+ ( Test A){ Test temp; temp.a=this->a + A.a; return temp; } }; int main() { Test b(10); Test a = b ; cout << a.a << endl; return 0; } The Output is:
$ ./Test Ctor 10 Cpy Ctor 10 10 It calls Copy constructor. Now, suppose If we modify the code as:
int main() { Test b(10); Test a = b + Test(5); cout << a.a << endl; return 0; } The Output becomes:
$ ./Test Ctor 10 Ctor 5 Ctor 0 15 The expression Test a = b + Test(5); does not call copy constructor. What I thought that that b+ Test(5) should be used to instantiate a new object a of type Test , so this should call copy constructor. Can someone explain the output?
Thanks
operator+you do not needtemp. You can useAdirectly.