Hi All
I was wondering that why in the below code, the copy construtor is called 2 times.
Code:
class A
{
private:
static int count;
int age;
public:
A()
{
cout<<"Inside A default Construtr= "<<++count<<endl;
}
A(int a)
{
cout<<"Inside A Parameter Construtr"<<endl;
age = a;
}
A(const A&x)
{
cout<<"Inside Copy Construtor"<<++count<<endl;
}
~A()
{
cout<<"Inside Destructor= "<<--count<<endl;
}
};
A f(A x)
{
return x;
}
int A:: count = 0;
int main()
{
A a;
A b= f(a);
return 0;
}
output is:
Inside A default Construtr= 1
Inside Copy Construtor=2
Inside Copy Construtor=3
Inside Destructor= 2
Inside Destructor= 1
Inside Destructor= 0
I think that when f(a) is called, since I am passing this as value, no copy constructor should be called. The copy constructor should called when the return object "x" is assigned to:
Can anybody through light why copy constructor called 2 times?
Thanks
nickman