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.