In problem given below, if argument is taken as constant variable of class then copy constructor is not called and if we remove const keyword then as usual copy constructor is called.
class A
{
int x,y;
public :
A()
{
cout<<"default constructor"<<endl;
}
A(const A &obj)
{
cout<<"copy constructor"<<endl;
}
};
/* when const is used in argument copy constructor is not
called when i return object by function in c++. but in place of " const A &obj "if we write A & obj then copy constructor is called */
A fun()
{
static A object;
return object; //function will return object
}
int main()
{
A obj1;
A obj2 = fun();
/*
Here copy constructor must be called but its not happening
because of that const in argument eg. A(const A&obj)
So my question is that why it is behaving like this
*/
return 0;
}
Aucun commentaire:
Enregistrer un commentaire