Reputation: 53
Using these two previous threads as examples
First thread: Why does overloaded assignment operator return reference to class?
Second thread: Why must the copy assignment operator return a reference/const reference?
Is the return type of an overloaded assignment operator a class or a reference to a class? I have seen both:
Point& Point::operator = (const Point& sourcePoint)
{
// As in the first thread I pasted above
return *this;
}
And
Point Point::operator = (const Point& sourcePoint)
{
// As in the second thread I pasted above
return *this;
}
Which is right?
Similarly, what's the difference between:
int exFunction()
{
int i = 5;
int* iPtr = &i;
return *iPtr;
}
Versus:
int& exFunction2()
{
int j = 5;
int* jPtr = &j;
return *jPtr;
}
Thanks!
Upvotes: 0
Views: 2162
Reputation: 477318
The two thigns are not "similar" at all.
First off, the assignment operators. They should return a reference to the object itself, so that you can use them in a chain:
Foo x, y, z;
x = y = z; // makes y equal to z and returns a reference to self,
// which is assigned to x
So it's always:
Foo & operator=(Foo const &) { /* ... */ return this; } // copy-assignment
Foo & operator=(/* any other signature */) { /* ... */ return this; }
Now, the second question: Your exFunction2
is completely wrong and broken. It has undefined behaviour, because it returns a reference to a local variable, which is out of scope by the time the function returns. (It says essentially return j;
; remember that the result of a dereference is an lvalue.) The only sensible way to write that function is like exFunction
, which can be shortened to int exFunction() { return 5; }
.
Here is a related question on this topic.
Upvotes: 1