Why should i use this?

Pages: 12
Hello everyone! I wrote the following code where i have two functions which do the same thing but in an different way. Take a look:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include<iostream>
using namespace std;


class one
{
    public:
        one(){};
        one(int k,int l):a(k),b(l){}
        one ad1(one& ena);
        one ad2(one& ena);
        void show() const{cout<<"a:"<<a<<",b:"<<b<<endl;}

    private:
        int a,b;
};


one one::ad1(one& ena)
{
    
    this->a+=ena.a;  //
    this->b+=ena.b;  //

    return *this;
}

one one::ad2(one& ena)
{
    
    return one((ena.a+a),(ena.b+b));
}

int main()
{
    one mia(7,2);
    one dio(5,6);
    one tria,tesera;

    tria=mia.ad1(dio);
    tria.show();

    tesera=mia.ad2(dio);
    tesera.show();

    
    return 0;
}


As you can see both ad1,ad2 do the same thing,but since i am not very experienced in using "this" pointer i would like to ask you which are the benefits of using it? I mean why should i prefer to use "this" instead of calling the constructor and passing directly values in it.

Also,Are there any cases where only "this" pointer can help me to do my job? For example in some operator overloading? Thank you for your time !
First of all,you should be returning a constant reference for what you trying to do,it is more efficient and will not allow to use the return as an lvalue.Second,ad1 looks redundant to me,i would choose ad2.As for the last question,sometimes you have no choice but to use the this pointer,like when you want to compare the whole object with another from within that object.Like on:

1
2
3
4
5
6
7
8
9
10

bool myClass::operator!=(const right &)
{


  return !(this==right); 


}
Last edited on
Nice example Sandy,thanks :) Maybe i could use it for something like that:

1
2
3
4
5
6
7
bool myclass::compare(const right& )
{
    if(this==right)
       return 1;
    else
       return 0;
}


is it right?
Yes that s' right,but redundant.Cheers.
cheers pal.
Hello kikirikou,


which are the benefits of using it?
no benefit other then making clear the correlation of the varibles (say 'a' is the member variable and not a local variable) so in you case you don't need 'this'

the difference between ad1 and ad2 is that ad1 modifies the member of the class while ad2 doesn't. That is a significant difference.

Mike Sandy wrote:
bool myClass::operator!=(const right &)
{


return !(this==right);


}
that's plain nonsense
@coder777

Wow,you are a genius.What he is asking is for a difference in functionality,not if the object is modified or not,that is why he is returning *this in ad1.If he didn't notice or does not know the difference between return by value and return by reference is out of the question.BTW,how can reusing an overloaded operator to implement another one be a nonsense?It is one of my favourites use of the this pointer and i don't see a better way of reusing code.Perhaps you can enlighten me.
ok Mike the 'operator!=' is not nonsense but !(this==right); is. You compare a pointer with a type.

I guess you mean something like this
1
2
3
4
bool myClass::operator!=(const right &r)
{
  return !operator==(r);
}


or
1
2
3
4
bool myClass::operator!=(const right &r)
{
  return !((*this) == r);
}


I know,i forgot to write "myClass" before the right &,but i assumed kikirikou would notice and didn't edit.I stay up very late and often make typos.Im sorry i made you angry.
Last edited on
@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.
Last edited on
Wow,now it results that only guys with 4000 posts can help with the questions.However those badass 4000 posts won't give you reading skills.As i told coder777 ,the OP is not asking if the object is modified or not,it is your ego that makes you want to point everything out right? It was not question,and evidently the snotty one is not me.Your first point about the functions being identical is exactly what i pointed out.Then you talk about local variables but it is a bad practice,there is no need for you to point it out and the OP probably doesn't care or already knows about it.As for operator overloading,again it is clear that you can't read:

Also,Are there any cases where only "this" pointer can help me to do my job? For example in some operator overloading?


Did i read operator overloading? Maybe for you it reads "the adventures of fu manchu",Mr.c++ expert.
Guys i appreciate everyone for his help.I know that everyone had a good intent to give me a hand,and indead you helped understand some things.I thank you all! peace brothers :)
What the hell is your problem, Mike Sandy?

All they did was point out the compiler errors that the OP and you both had in your posts, and advise a few ways the code could be improved.

Either grow up or go away.
@Mike Sandy
Please... calm down. We're not out to get you; we just pointed out a few compile errors. The more mature members of this community would probably laugh it off. I know I would, after banging my head against the desk. Why not take an example? :)

@Duoas
I don't mean to poke at the fire, and I know you edited your post, but... please. There's no need for some of your more explosive reactions either. Please?

@Disch
Can't we all just get along?

-Albatross

EDIT: Dangit! That first "1" in my post count made me lose at the slot machine!
Last edited on
@Disch
Can't we all just get along?

=P

Normally I try to be pleseant, but this guy really burns me.

Just about everything he said in his original reply was totally wrong, and as soon as someone steps in and corrects him, he explodes in a fit of "YOU'RE NOT BETTER THAN ME!!!" rage.

Had I responded earlier in the thread, my tone would have been more polite. But now having seen his reaction to others' posts, whatever.

I won't apologize for my previous post or for this one. If Mike Sandy can't get a grip on his anger and insecurity issues, I think it's better for everyone if he just goes elsewhere. I stand by that.


EDIT:

bah it's not worth it. you're right Albatross (note: not an apology, just a "give up")
Last edited on
Alright guys.Another typical forum .5 or 6 cats with over 9000 posts trying to dismiss the rest because they think they are better.Im out of here.
@Disch

How much can you bench press?
Are you attempting to find something you are better at than he is? If so, that's fairly low, and could go on all day (assuming Disch has talents beyond programming :P). Regardless, you shouldn't upset yourself over what anyone said, but you may want to see if what you said was off limits.
Last edited on
Alright guys.Another typical forum .5 or 6 cats with over 9000 posts trying to dismiss the rest because they think they are better.


You're absolutely right. It's all us. It couldn't possibly be because you're a hothead who thinks he knows more than everyone else.

Let's recap the events here:

1) OP asks a question
2) You give decent response but you have several errors in your code
3) regular poster corrects you and shows syntax that will actually compile
4) you fly off the handle and accuse everyone of being elitists

You need to learn to take corrections/criticism better. Especially if you're going to post code that's all wrong.

EDIT: Actually upon reviewing the events, it was actually coder777 who corrected you... and he only has 114 posts. So really your whole point is a sham.

Duaos' post was addressing something else the OP asked about that neither you nor coder777 addressed. Why you exploded at him for providing additional info is a great mystery to me. Maybe you're just allergic to users with high post counts.

/EDIT

Im out of here.


Bye. I sure won't miss you.

But I somehow doubt this goodbye was genuine.

How much can you bench press?


I'm not sure. What I do know is that my post count, and therefore my penis, is bigger than yours.
Last edited on
Move along...nothing to see here...just another guy that can't take being wrong...
Pages: 12