Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

double colon for instance variables in c++

Tags:

c++

I have always been under the impression that <class>::<variable> is for accessing static members. However, I am surprised to find out that the following compiles just fine. (I would have used this-> as shown in the inline comment.)

Further investigation on Google/StackOverflow doesn't show anything pertinent to this behavior, I wonder if anyone could shed some light on this.

class Test {
    private:
        int x;
    public:
    void set_x(int x) {
        // this->x = x;
        Test::x = x;
    }
};

int main(int argc, char *argv[])
{
    return 0;
}

ENV: clang version 7.0.0- (trunk)

like image 751
Albert Netymk Avatar asked Nov 29 '25 15:11

Albert Netymk


1 Answers

The :: is the scope-resolution operator and can be used to specify which of a number of symbols of the same name but different but visible scope the reference refers to.

Either scope-resolution or this-> may be used in this example, but scope-resolution itself has more general applicability within the language.

like image 190
Clifford Avatar answered Dec 02 '25 05:12

Clifford



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!