We know copy constructor is required either of the following scenario :
1) when we try to intialize one object using another object.
2) When we try to pass an object by value to a function or
3) when we return an object by value from a function.
I have written the following code just to test all the scenarios the first one worked well. Second one also didn't throw any error but it didn't give the desired result
#include<iostream>
usingnamespace std;
class c_const
{
int x;
int y;
public :
c_const(int a, int b)
{
cout <<"in constructor!!"<<endl;
x = a;
y = b;
}
void print()
{
cout << "x " << x << endl;
cout << "y " << y << endl;
}
~c_const()
{
cout << "detructed " << endl;
cout << "x_d " << x <<endl;;
cout << "y_d " << y << endl;;
}
c_const( c_const & pp)
{
cout <<"in copy constructor!!!"<< endl;
x = pp.x;
y = pp.y;
}
};
void func(c_const & cp)
{
cout <<"hey ya "<<endl;
cp.print();
}
c_const & func1 (int x , int y)
{
c_const pq(5,6);
cout << x << endl;
cout << y << endl;
return pq;
}
int main()
{
{c_const cc(10,20);
// c_const cc1(cc);
//c_const cc2 = cc1;
// cc2 = cc1;
cc.print();
// cc1.print();
func(cc);
c_const rr(7,8);
rr = func1(2,3);
}
system("pause");
return 0;
}
}
When I am calling the function from main and passing an object by value to it copy constructor is not getting called same thing is happening when I am trying to return an object by value from a function as in the code.. please tell me where am I wrong?
Well you're returning a reference to that object, so the copy constructor is not going to be called. Change that function signature to return a copy, and then you'll see it being called.
Same goes for the func(). Change the parameter to be passed by value instead of by reference.
The technical reason is a temporary object cannot bind to a non-const reference.
A more intuitive (?) reason is because you don't want to be changing that object, and marking objects as const is a good defensive programming technique.