1

I started using C++ for object oriented programming and I've come across static member variables.

In my particular case, I have the following in my header file (Class.hpp):

private:
    const static string DEFAULT_PATH;
    static string path;

Not that really matters, but is as valid as any example.

So, to do the proper initialisations I had to do some research and find out that this can't be done in the class body and has to be done in the source (Class.cpp) file. In my source file, I added:

const string Class::DEFAULT_PATH = "./";
string Class::path = DEFAULT_PATH;

I found this to be counter-intuitive, but tried to deal with it. Then I wondered:

  • When exactly did the compiler call this initialization code? How can I assume when will this fields have a value? I don't really understand what's happening there and I'd like to know.

  • And what's most intriguing for me: which symbols can I see whithin Class.cpp when including class.hpp? And why those declarations have be outside the class body and in another file?

Setzer22
  • 1,589
  • 2
  • 13
  • 29
  • It's initialized before `main`. Don't count on any order before that. And the *definition* has to go in the .cpp so you don't violate the One Definition Rule. – chris Jun 06 '14 at 20:58
  • The compiler sees .cpp files, include are substituted by the preprocessor in the .cpp file with the .h file content. – 101010 Jun 06 '14 at 20:58
  • Possible duplicate: http://stackoverflow.com/q/1421671/1227469 – JBentley Jun 06 '14 at 21:01
  • @KerrekSB Well my goal today was to learn to use classes and do OO-programming in C++ as weird as it may seem. Just for learning purposes I could say. – Setzer22 Jun 06 '14 at 21:26

1 Answers1

3
  • Static members are initialized before the main starts, so they are already initialized in your main. Non static members of the class are initalized in the constructor.
  • If you want to enforce the initialization order (which is the case because one variable refers to the other), you can use a function to initalize the function C++ static initialization order.
  • boost::call_once (or its c++11 equivalent) can help you for that. http://www.boost.org/doc/libs/1_31_0/libs/thread/doc/once.html
  • The standard tells you that it has to be initalized somewhere outside the class definition, so generally you do it on the cpp file
  • Once this is done you can access the variables with Class::static_member
Community
  • 1
  • 1
Gabriel
  • 3,564
  • 1
  • 27
  • 49