Reputation: 779
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?
Upvotes: 10
Views: 2037
Reputation: 27248
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.
Upvotes: 7
Reputation: 3048
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.
Upvotes: 6
Reputation: 36896
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.
Upvotes: 14