1

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;
    }
1
  • Hi arm.u and welcome to stackoverflow! I'd recommend that you tidy up your question a bit to make it more clear what you are trying to do. On the face of it, your getters and setters are, well, completely different methods with different purposes, so it is hard to judge which is "preferred". Can you tell us more detail?
    – Wheezil
    Commented Jan 11, 2019 at 1:14

1 Answer 1

8

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:

  • Always suffix member variables with _, like health_
  • Always prefix member variables with m_, like m_health

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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