return a reference

heeyy
when should i return this and when should i return *this in class functions?

1
2
3
4
5
6
 CVector& CVector::operator= (const CVector& param)
{
  x=param.x;
  y=param.y;
  return *this;
}

I get that in order to return *this the function must return a reference to the class, i don't get when csn i return this (not *this)

And why this function gets a reference object? Can't we get access to param.x without the &?
Thank you
this is a pointer to the current object begin worked on. So, for example in this snippet:
1
2
CVector vec1, vec2(1,0);
vec1 = vec2;

The this points to the vec1 object. Then when you derefence this(*this), you get the object itself. That is why, when you return a reference, you want to return a reference to the object and not the pointer.

If for some reason, your function needs to return a pointer to the object being worked on, you need a different return type:
1
2
CVector*& CVector::pointer_to_this()
    {return this;}

Note that if you have a function like this, try not to call it on rvalue (or temporary) objects.

Of course, by convention, assignment operators return a reference to allow operator chaining, like:
 
vec1 = vec2 = vec3 = vec4;

You could return a value, but that value would be temporary and would make the chaining practically useless.

And why this function gets a reference object? Can't we get access to param.x without the &?

Are you speaking of the parameter? When you pass objects, you would usually pass by reference to make your program more efficient. If you pass by value (and the function doesn't need to make a copy), the function would be making an unnecessary copy when you could access the original object directly. Then, the const comes in to protect the object from changes (because when you write vec1 = vec2 you wouldn't expect vec2 to change).

Hope this helps.
Last edited on
A reference parameter saves a temporary.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
a = b;
// pseudo expands to
a.x = b.x;
a.y = b.y;

// a non-reference version would do
CVector param( b );
a.x = param.x;
a.x = param.y;
// which expands further to
param.x = b.x;
param.y = b.y;
a.x = param.x;
a.x = param.y;

Furthermore:
1
2
3
4
5
6
7
8
9
CVector& CVector::operator= (const CVector& param)
{
  if ( &param != this ) // guess, why this is good
    {
      x=param.x;
      y=param.y;
    }
  return *this;
}


this is a pointer that points to the object, whose member function is being called. If the member returns a pointer to self, then you return this. Here the returned value is a reference. Conversion rules between values, references, and pointers ...
Topic archived. No new replies allowed.