Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using scope operator to access non-static member variables

Tags:

c++

scope

It's a fact that you can explicitly access member variables (inside a member function, and not particularly a constructor) using this syntax : this->member_name (i.e. to distinguish with a function argument with the same name).

Besides this, I thought that the syntax ClassName::static_member was reserved to access static members outside of a class.

Then I was surprised when I realized that the following set_2() method was working as one could expect:

#include <iostream>

struct A {
    int x;
    // The two following methods seem to act similarly:
    void set_1(int x) { this->x = x; }
    void set_2(int x) { A::x = x; }
};

int main ()
{
    A a;

    a.set_1(13);
    std::cout << a.x << std::endl;

    a.set_2(17);
    std::cout << a.x << std::endl;

    return 0;
}

Output:

13
17

Is is a good and valid practice to use the scope operator (A::x) in this case? I would personnally prefer it, instead of using the this->x syntax.

like image 230
yolenoyer Avatar asked Mar 02 '26 02:03

yolenoyer


2 Answers

Using A::x in this case is valid, but I think this->x is more idiomatic and less error-prone (the reader of the code can immediately see that x is a member of the class, without thinking what A is).

like image 104
Eugene Avatar answered Mar 03 '26 15:03

Eugene


According to the C++ Standard (3.3.7 Class scope)

2 The name of a class member shall only be used as follows:

— in the scope of its class (as described above) or a class derived (Clause 10) from its class,

— after the . operator applied to an expression of the type of its class (5.2.5) or a class derived from its class,

— after the -> operator applied to a pointer to an object of its class (5.2.5) or a class derived from its class,

— after the :: scope resolution operator (5.1) applied to the name of its class or a class derived from its class.

For example data members of methods of a derived class can hide data members and/or methods of its base class. To access data members and nethods of the base class you can use the scope resolution operator.

struct Base
{
    virtual ~Base() {};
    virtual void Hello() const { std::cout << "Base" << std::endl; }
};


struct Derived : Base
{
    virtual void Hello() const 
    { 
        Base::Hello();
        std::cout << "and Derived" << std::endl; 
    }
};

Derived d;

d.Hello();
like image 20
Vlad from Moscow Avatar answered Mar 03 '26 16:03

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!