Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing members from an object itself with either THIS or member scope

Tags:

c++

class

What is the proper way of accessing a member data/function that is part of the method's class? There appears to be 3 means:

class test{
    private:
        int variable;
    public:
        void setVariable(int value) {
            variable = value;        // method 1, using the variable name directly
            this->variable = value;  // method 2, via pointer dereference of 'this'
            test::variable = value;  // method 3, via scope operator
        }
};

They all seems to work as far as I can tell. Are they equivalent? Is there a reason to use one over the other beside style/consistency?

like image 808
Peter Avatar asked Dec 30 '25 00:12

Peter


1 Answers

In addition to style and consistency, as you mention, sometimes you have to use a specific syntax to disambiguate.

"method 2" can be used to disambiguate between local variables and class members.

"method 3" can be used to disambiguate between fields with the same name in different places of your class hierarchy.

like image 82
Magnus Hoff Avatar answered Jan 01 '26 15:01

Magnus Hoff