S
subramanian100in
consider the following program:
#include <iostream>
using namespace std;
class Test
{
public:
Test(int xx) : x(xx) { cout << x << endl; }
Test add(const Test & obj);
Test(const Test & obj) : x(obj.x)
{ cout << "copy ctor " << x << endl; }
int x;
};
Test Test::add(const Test & obj)
{
return x + obj.x;
}
int main()
{
Test a(10);
Test b(20);
cout << a.add(b).x << endl;
return 0;
}
This program compiles fine and produces the following output
in both g++ and VC++ Express Edition 2005
10
20
30
30
I thought the copy ctor would be called when we invoke a.add(b)
because Test::add() returns an object of Test type and here
I expected the copy ctor to be called.
I do not understand why the copy ctor is not called.
Is it optimized away ? Or this is the expected behaviour.
Kindly clarify.
Thanks
V.Subramanian
#include <iostream>
using namespace std;
class Test
{
public:
Test(int xx) : x(xx) { cout << x << endl; }
Test add(const Test & obj);
Test(const Test & obj) : x(obj.x)
{ cout << "copy ctor " << x << endl; }
int x;
};
Test Test::add(const Test & obj)
{
return x + obj.x;
}
int main()
{
Test a(10);
Test b(20);
cout << a.add(b).x << endl;
return 0;
}
This program compiles fine and produces the following output
in both g++ and VC++ Express Edition 2005
10
20
30
30
I thought the copy ctor would be called when we invoke a.add(b)
because Test::add() returns an object of Test type and here
I expected the copy ctor to be called.
I do not understand why the copy ctor is not called.
Is it optimized away ? Or this is the expected behaviour.
Kindly clarify.
Thanks
V.Subramanian