Search code examples
c++thisc++17static-membersthis-pointer

Doesn't static class members have no association with the this pointer?


Take this example:

SomeClass.h

class Foo {
public:
    static int bar;
    int x;
    void someFunc() {
        this->x = 5;
        this->bar = 9;
    }
};

SomeClass.cpp

int Foo::bar = 0;

mainc.pp

#include <iostream>
#include "SomeClass.h"

int main() {
    Foo f;
    f.someFunc();

    std::cout << "f.x = " << f.x << '\n';
    std::cout << "f.bar = " << f.bar << '\n';
    return 0;
}

Compiled and built with Visual Studio 2017CE.

Output

f.x = 5
f.bar = 9

However according to cppreference:static

Static members of a class are not associated with the objects of the class: they are independent variables with static or thread (since C++11) storage duration or regular functions.

Now as for static member functions they state:

Static member functions are not associated with any object. When called, they have no this pointer.

I just want some clarity on this: I had thought that both static members and static function members did not have the this pointer associated with them...


Solution

  • They aren't associated with the this pointer in your example. Rather, they happen to be accessible via the this pointer (for the same reason, f.bar = 10; would have been legal too).

    This is covered explicitly in the C++ standard. See section "[class.static] Static members" (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4713.pdf), which states:

    A static member s of class X may be referred to using the qualified-id expression X::s; it is not necessary to use the class member access syntax (8.5.1.5) to refer to a static member. A static member may be referred to using the class member access syntax, in which case the object expression is evaluated.

    [ Example:

    struct process {
      static void reschedule();
    };
    process& g();
    
    void f() {
      process::reschedule(); // OK: no object necessary
      g().reschedule(); // g() is called
    }
    

    — end example ]