the benefit of "this" pointer ?

hi guys

i know what's this pointer is,but i don't figure out what's it's benefit other than returning the instance of the current object !

another benefit (which i see it's usless) is using it to deal with local instance variables,which u can use them without using the pointer !

am i right ? and is there any other use of it ?
Here it can be useful (although it can be prevented by good naming):
1
2
3
4
5
6
7
8
9
10
11
12
class SomeClass {
    int a;
    int b;

    public:
        SomeClass( int a, int b );
};

SomeClass::SomeClass( int a, int b ) {
    this->a = a;
    this->b = b;
}


And you can chain member functions using this :
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
class SomeClass {
    int a;
    int b;

    public:
        SomeClass& Multiply();
        SomeClass& Divide();
};

SomeClass& SomeClass::Multiply() {
    a *= b;

    return *this;
}

SomeClass& SomeClass::Divide() {
    a /= b;

    return *this;
}

int main( int argc, char* argv[] ) {
    SomeClass theClass;

    theClass.Multiply().Divide(); // this is possible because Multiply() returns 
                                                // a reference to theClass
    return 0;
}
Last edited on
i know what's this pointer is,but i don't figure out what's it's benefit other than returning the instance of the current object !
You have to thing about the object is used.

In C, it is not uncommon to see code like:
1
2
int i, j, k, sum;
i = j = k = sum = 0;


How can we write code like:
1
2
std::string a, b, c, name;
a = b = c = name = "empty";


We can do that if we make operator= return a reference to the object (rather than a pointer to it). So one that sense, it can be thought of as syntactic sugar. But more importantly, it's providing an effect that we want.

another benefit (which i see it's usless) is using it to deal with local instance variables,which u can use them without using the pointer !
I never use this->x to access member variables. Personally, I think it shows lack of familiarity with the language.
Topic archived. No new replies allowed.