C++ static const access through a NULL pointer [duplicate]

class Foo {
public:
 static const int kType = 42;
};

void Func() {
 Foo *bar = NULL;
 int x = bar->kType;
 putc(x, stderr);
}

Is this defined behavior? I read through the C++ standard but couldn't find anything about accessing a static const value like this... I've examined the assembly produced by GCC 4.2, Clang++, and Visual Studio 2010 and none of them perform a dereference of the NULL pointer, but I'd like to be sure.


Solution 1:

You can use a pointer (or other expression) to access a static member; however, doing so through a NULL pointer unfortunately is officially undefined behavior. From 9.4/2 "Static members":

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 (5.2.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.

Based on the example that follows:

class process {
public:
    static void reschedule();
};

process& g();

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

The intent is to allow you to ensure that functions will be called in this scenario.

Solution 2:

I believe that the actual value of the type is not used at all when calling

bar->kType

since kType is static, and bar is of type Foo it is the same as calling

Foo::kType

which you should really be doing anyway for clarity.

Calling bar->kType gives a compiler warning on most platforms for this reason.