1

Consider the following C++ code:

class MyClass
{
    private:
        static int y;
    public:
        static void setY(int t) { y = t; }
        int getY() {return y;}
};
int MyClass::y = 0;
int main()
{
    MyClass mc, mc1;
    MyClass::setY(10);
    cout << mc.getY() << endl; //prints 10
    mc1.setY(12);
    cout << mc.getY() << endl; //prints12
    return 0;
}

Why do we have to declare int MyClass::y=0; before main ? If we comment that out, we will get an error message such as "undefined variable y". Didn't we just define it in the class? Also, why does it have to be global? Why can't we put int MyClass::y=0; in the main function?

king_nak
  • 11,313
  • 33
  • 58
Thenewstockton
  • 443
  • 6
  • 18

0 Answers0