Reputation: 75
I've tried to figure out what is the purpose of & on the return type. I mean,consider the code below, what happens if i delete & from the operator overloading function.
class Container
{
public:
int numElems;
int *data;
Container(int n):numElems(n){data=new int [numElems];}
Container & operator=(const Container &rhs)
{
if(this!=&rhs)
{
if(data!=NULL)
delete [] data;
numElems=rhs.numElems;
data=new int [numElems];
for (int i=0;i<numElems;i++)
{
data[i]=rhs.data[i];
}
return *this;
}
}
};
I deleted it and compile it ,it compiled without any errors.Actualy it gives the same result in both cases for an example main:
int main()
{
Container a(3);
Container b(5);
Container c(1);
cout<<a.numElems<<endl;
cout<<b.numElems<<endl;
cout<<c.numElems<<endl;
a=b=c;
cout<<a.numElems<<endl;
cout<<b.numElems<<endl;
cout<<c.numElems<<endl;
return 0;
}
So, is there anyone who can help me about the purpose of & on the left side ? Thanks in advance.
Upvotes: 1
Views: 113
Reputation: 543
class foo {
public:
int val;
foo() { }
foo(int val) : val(val) { }
foo& operator=(const foo &rhs) {
val = rhs.val;
return *this;
}
foo& operator++() {
val++;
return *this;
}
};
void main() {
foo f1(10), f2;
(f2 = f1)++;
std::cout << f1.val << " " << f2.val << std::endl;
}
Output:
10 11
Output when removing reference:
10 10
Upvotes: 1
Reputation: 17026
If you don't return a reference, you implicitly make an extra unnecessary copy.
Upvotes: 0
Reputation: 18750
Returning a reference is much faster than returning a value for a large object. This is because under the hood a reference is just a memory address whereas if you return it by value it requires a deep copy
Upvotes: 0