0

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

3

1 Answer 1

2

See copy elision: http://en.wikipedia.org/wiki/Copy_elision

Basically, no temp is constructed and result is put directly into Test a object.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.