1

I am beginner to C++ and have a doubt about static member variables and member functions.

I have implemented a class as follows -

class Foo
{
private:
    static int myVariable;
public:
    static void setMyVariable()
    {
        myVariable = 100;
    }

    static void resetMyVariable()
    {
        myVariable = 0;
    }
};

There are following considerations when I wrote a code like that -

  • I want only one instance of class Foo. Thats why I made all member variables and functions as static.
  • I don't want the outside code to touch myVariable

I have put this class in a header file and included in my main file. When I do this, I get an error undefined reference to Foo::myVariable

I want to know if I can write a code which can satisfy above requirements?

Thanks !

Raj
  • 3,300
  • 8
  • 39
  • 67

1 Answers1

2

You need to define static class variables somewhere: e.g. in your main C++ file,

int Foo::myVariable;

Note that technically, by making everything static, you may have no instances of Foo.

doctorlove
  • 18,872
  • 2
  • 46
  • 62
  • thanks for the answer. I understood now what you mean and with other previous comments. Since now I have to define this variable in main, does it mean that it is exposed outside and no longer private. – Raj Dec 31 '13 at 10:28
  • 1
    @Raj No, it's not exposed. Access control still applies when referring to the variable. – Angew is no longer proud of SO Dec 31 '13 at 10:30