10
class TConst
{
    const int i;
    int& ref;
    public:
    TConst(int n):i(n),ref(n){}
    static void p1(){prn(i);}//error here
};

My compiler generates an error when I try to use a const class member in a static member-function.

Why is it not allowed?

3
  • 1
    Please always post the full error that you get.
    – orlp
    Commented Dec 28, 2011 at 18:05
  • 1
    const int is still bound to an object, not to class.
    – nullpotent
    Commented Dec 28, 2011 at 18:07
  • 1
    In a static method there is no class instance so there are no class members ... FYI you can make this static const int i = 42; if you want to use it this way.
    – AJG85
    Commented Dec 28, 2011 at 18:12

3 Answers 3

14

const means different things. In this case, it means that i is immutable after it's been initialized. It doesn't mean it's a literal constant (like I believe you think it means). i can be different for different instances of TConst, so it's logical that static methods cannot use it.

1
  • It's always so simple ) Thanks
    – Alexander
    Commented Dec 28, 2011 at 18:12
7

It wouldn't work even if it wasn't const:

error: a nonstatic member reference must be relative to a specific object

Static functions can not access non-static member variables. This is because non-static member variables must belong to a class object, and static member functions have no class object to work with.

6

The const member is initialized during the object construction. The static members are not dependent on the object creation and don't have access to this pointer hence they don't know where your const member variable resides.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.