@
Mike Sandy
You are out of your league, so don't get snotty.
Modifying the object very much is a difference in functionality, even if you want to get really, really technical about the meaning of the word "functional requirement".
Second, you have not addressed the OP's concern, but rather interjected an unrelated concern: operator overloading. The OP is not playing with operator overloading, he only wants to know which method is a better choice with respect to the this pointer, and why. You have failed to respond to that and have given incorrect advice. So put your soapbox away.
[edit] Sorry to grouch at you then... [/edit]
@
kikirikou
The
this pointer is used whether or not you realize it in both examples. The difference is as
coder777 indicated: sometimes you need it to be clear about what variable you are using. The following two snippets are identical:
22 23
|
this->a+=ena.a; //
this->b+=ena.b; //
|
22 23
|
a+=ena.a; //
b+=ena.b; //
|
The trick is when you have local variables that may get in the way:
1 2 3 4 5 6 7 8 9
|
struct point_t
{
int x, y;
void add( int x, int y )
{
this->x += x; // here, we must use this, because "x" means the argument x...
this->y += y; // ...unless otherwise specified, which we do with "this->x"
}
};
|
As also indicated to you, the first function (starting on line 19)
modifies your object, when the other function (starting on line 28) does not. To make sure it does not modify your object, create a new object inside your function and play with it instead:
19 20 21 22 23 24 25 26 27
|
one one::ad1(one& ena)
{
one result; // this is the new object...
result.a = a + ena.a; //
result.b = b + ena.b; //
return result; // ...which we return here
}
|
Here is another way of writing that:
19 20 21 22 23 24 25 26 27
|
one one::ad1(one& ena)
{
one result( a, b ); // ...or "one result( this->a, this->b );", etc
result.a += ena.a;
result.b += ena.b;
return result;
}
|
The best way of writing the exact same thing, though, is what you have as your second function:
1 2 3 4
|
one one::ad2(one& ena)
{
return one( a+ena.a, b+ena.b );
}
|
Finally, as a matter of "const-correctness", if you have things that should not get modified, you should list them as
const:
1 2 3 4
|
one one::add( const one& ena ) const
{
return one( a+ena.a, b+ena.b );
}
|
What this says is two things: 1) the argument is never modified, and 2) the function does not modify *this object.
Hope this helps.