When [abc e = a+b] is called, the copy constructor is not called.
class abc{
int i;
public:
abc()
{
i = 10;
cout<<"constructor"<<endl;
}
abc(const abc &a)
{
cout<<"copy constructor"<<endl;
i = a.i;
}
abc operator=(const abc &a)
{
cout<<"operator="<<endl;
abc temp;
temp.i = a.i;
return temp;
}
abc operator+(abc& a)
{
cout <<"Operator+ called"<<endl;
abc temp;
temp.i = i+a.i;
return temp ;
}
};
int main()
{
abc a,b;
cout <<"----------------------------------------------"<<endl;
a = b;
cout <<"----------------------------------------------"<<endl;
abc c = a;
cout <<"-----------------------------------------------"<<endl;
abc d(a);
cout <<"-------------------------------------------"<<endl;
**abc e = a+b;**
}
However if the overload operators methods are replaced with the following methods that return references to the object of class abc, copy constructor gets called.
abc& operator=(const abc &a)
{
cout<<"operator="<<endl;
i = a.i;
return *this;
}
abc& operator+(const abc& a)
{
cout <<"Operator+ called"<<endl;
i = i+a.i;
return *this ;
}
Can some one please explain why does this happen?