#include <iostream>
using namespace std;
class X
{
public:
X() { cout<<"default constructor"<<endl; }
X(const X&) { cout<<"copy constructor"<<endl; }
};
X test(X a)
{
X y = a;
return y;
}
int main()
{
X obj;
X obj1 = test(obj);
return 0;
}
Output:
default constructor
copy constructor
copy constructor
I had compiled the using MinGw compiler.
But, I think the output is wrong.
The copy constructor is called when an object is passed by value, return by value or explicitly copied.
In the above program, the "copy constructor"
has to be called 4 times.
test(obj)
is called, to copyobj
toa
X y = a
is called, explicitly copied.return y
is called,y
is copied to a temporary object, let it betemp
X obj1 = temp
, explicitly copied.
Please correct me. Provide your justification too..