R
Rahul
Hi Everyone,
I was overloading the operator= function as a class member function,
#include <iostream.h>
class A
{
int value;
public : A& operator = (const A& ref)
{
this->value = ref.value;
cout<<"in"<<endl;
return *this;
}
A(int value) : value(value)
{
}
A(const A& copy)
{
this->value = copy.value;
cout<<"copy with a value of "<<copy.value<<endl;
}
void print()
{
cout<<"value is"<<value<<endl;
}
};
int main()
{
A obj(0);
A obj1(10);
A obj2(20);
obj.print();
obj1.print();
obj2.print();
obj1 = obj = obj2;
obj.print();
obj.print();
obj2.print();
}
It works fine and all objects have a value of 20 as expected...
Next i changed the return type of the operator = function, like
so that it returns an object instead of a reference...
A operator = (const A& ref)
{
this->value = ref.value;
cout<<"in"<<endl;
return *this;
}
And as the object is returned by value, each call to operator= also
invokes the copy constructor for the temp object, which is again
passed to the operator= function, and the end result happens to be
same as with operator= function which returns a reference.
Is there any thumb rule while overloading operators, when we have
alternative implementations?
Thanks in advance!!!
I was overloading the operator= function as a class member function,
#include <iostream.h>
class A
{
int value;
public : A& operator = (const A& ref)
{
this->value = ref.value;
cout<<"in"<<endl;
return *this;
}
A(int value) : value(value)
{
}
A(const A& copy)
{
this->value = copy.value;
cout<<"copy with a value of "<<copy.value<<endl;
}
void print()
{
cout<<"value is"<<value<<endl;
}
};
int main()
{
A obj(0);
A obj1(10);
A obj2(20);
obj.print();
obj1.print();
obj2.print();
obj1 = obj = obj2;
obj.print();
obj.print();
obj2.print();
}
It works fine and all objects have a value of 20 as expected...
Next i changed the return type of the operator = function, like
so that it returns an object instead of a reference...
A operator = (const A& ref)
{
this->value = ref.value;
cout<<"in"<<endl;
return *this;
}
And as the object is returned by value, each call to operator= also
invokes the copy constructor for the temp object, which is again
passed to the operator= function, and the end result happens to be
same as with operator= function which returns a reference.
Is there any thumb rule while overloading operators, when we have
alternative implementations?
Thanks in advance!!!