If there is a class
class complex
{
private:
float real,imag;
public:
complex operator +(complex c)
{
complex t;
t.real=real+c.real;
t.imag=imag+c.imag;
return t;
}
and in main if we call overloaded operator by
c3=c1+c2;
then compiler internall converts as c3=c1.operator+(c2)
similarly in similar example of operator overloading,chaining of =
class circle
{
private:
int radius;
float x,y;
public:
circle()
{}
circle(int rr,float xx,float yy)
{
radius=rr;
x=xx;
y=yy;
}
circle& operator=(const circle& c)
{
cout<<endl<<"assignment operator invoked";
radius=c.radius;
x=c.x;
y=c.y;
return *this;
}
int main()
{
circle c1 (10,2.5,2.5);
circle c2,c3;
c3=c2=c1;
c1.showdata();
c2.showdata();
c3.showdata();
return 0;
}
Overloaded = to operator will be called 2 times first for c2=c1 and then for c3=c2.
then how will compiler treat c2=c1 with its function prototype??how will compiler internally convert this overloaded operator = call??(plz tell in reference with above addition example)
Whose private fields will b accessed and to ahich object value will be returned??
is similarly evaluated as
c2.operator=(c1)returns a reference toc2after it was assignedc1.Note that for your class, you don’t need to overload
operator =since the compiler-generated one does the exact same thing.And if you do, you should obey the rule of three – and also add a destructor and copy constructor. But, again, your class doesn’t require either.