Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we use const members in static member functions?

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?

like image 487
Alexander Avatar asked Dec 28 '11 18:12

Alexander


1 Answers

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.

like image 171
tenfour Avatar answered Sep 25 '22 14:09

tenfour