c++thisthis-pointer

Do I need the "this pointer" in my class methods?


Is there any difference between getA()&getB() and setA()&setB() ?

If they are the same, which is the preferred syntax?

    class A{
    public:
        int x;

        int getA(){return x;}
        int getB(){return this->x;}
        void setA(int val){ x = val;}
        void setB(int val){ this->x = val;}

    };

    int main(int argc, const char * argv[]) {
        A objectA;
        A objectB;

        object.setA(33);
        std::cout<< object.getA() << "\n";

        objectB.setB(32);
        std::cout<< object.getB() << "\n";

        return 0;
    }

Solution

  • It's the same in your use case. It's usually preferred to omit this-> when possible, unless you have a local coding style guide / convention.

    It matters when you have a local variable or parameter that shadows the member variable. For example:

    class Enemy {
    public:
        int health;
        void setHealth(int health) {
            // `health` is the parameter.
            // `this->health` is the member variable.
            this->health = health;
        }
    };
    

    Optionally, this can be avoided by having a naming convention in your project. For example: