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 !

4
  • 1
    See here. Commented Dec 31, 2013 at 10:22
  • 1
    If you only want one instance you should take a look at the singleton pattern (now flame me haters ;) ) Commented Dec 31, 2013 at 10:54
  • You want a set of free functions and a static global variable in a separate C++ file, neither a singleton or a class with only static members Commented Dec 31, 2013 at 11:02
  • 1
    Singletons can be an evil thing. But if he wants only one instance of the class, then he probably wants non-static member variables with a Singleton pattern in preference to a whole batch of static stuff. Commented Dec 31, 2013 at 11:06

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 No, it's not exposed. Access control still applies when referring to the variable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.