-3

I apologize for asking this intuitive question. I'm not good at programming and my recent work requires me to work a lot with SDEs. I wonder what might be the advantages using the this pointer?

I understand why it exists, and sometimes "this" makes it clear we are assigning value to a member variable (in the following example). For derived class, since we are able to access the base class protected or public member functions and data members even without using this->. I wonder what could be the other advantages?

class Test
{
private:
    int x;
public:
    void setX (int x)
    {
        // The 'this' pointer is used to retrieve the object's x
        // hidden by the local variable 'x'
        this->x = x;
    }
    void print() { cout << "x = " << x << endl; }
};
9
  • I'm new to programming. I did my search and prepared my question well (using my standard). Please consider this before you downvote. Thank you.
    – Ali
    Jul 29 at 17:58
  • First of all, please include code as code, not pictures. Jul 29 at 17:59
  • It's not really clear what you mean when you ask about "advantages". Advantages compared to implicitly accessing members? How would you rewrite this->x = x in a way that achieves the same effect without using "this->"?
    – Alexander
    Jul 29 at 18:04
  • If I'm not mistaken, this sort of question is off-topic here. In any case, when you create an instance (an object) of your Test class (and you could have several different instances), the this pointer allows each instance to refer to itself, from inside its own functions. Generally speaking, you don't have to pay too much attention to it, you won't be using it all that often, but it lets you do certain things. One is to access a field hidden by a local variable of the same name. You can return this from a method, which lets you chain method calls (search for "C++ method chaining"). 1/2 Jul 29 at 18:37
  • There are also uses that are less technical in nature - e.g., a developer team might decide to always write this-> for member access, so that it's clear to everyone (when reading other people's code) that a member is being accessed, as opposed to a static function or a free function of some library, etc. I'm not personally a big fan of that. Or, you could just do it to take advantage of code completion in your IDE, to list all the members available on the instance. 2/2 Jul 29 at 18:37

1 Answer 1

5

I wonder what could be the other advantages?

You can pass yourself to others. You can build others that know who you are. The visitor pattern wouldn't be easy to write without this. And the classic "getThis trick" doesn't work very well without it. It makes subscribing easy in the observer pattern.

Sometimes an object needs to know where it lives so it can tell others. Just like business men need business cards full of info they already know.

Not the answer you're looking for? Browse other questions tagged or ask your own question.