GrinNare
GrinNare

Reputation: 125

C++ Static Class Member Initializing

I'm new to C++ and still in learning phase, so this may be a simple and probably dumb question to you ;(

From other questions and answers on the board, I learned that it is customary and preferred to initialize the private static class data member in the cpp file along with the other member function definitions.

However, could it be possible to initialize the member function as global variable in main.cpp? Since all objects should share one static data member, why not just initialize it there? (I would think initializing it in main itself, but I would guess this would spit out a compilation error)

Could you please explain if this is technically not plausible or just not done conventionally. Since the static data member is initialized in class cpp file as a global variable anyways, I do not see a reason why initializing it in main cpp will fail. Please advise.

Upvotes: 1

Views: 216

Answers (1)

Zereges
Zereges

Reputation: 5209

Suppose following header file class.hpp

#pragma once // sort of portable
struct C // to make the example shorter.
{
    static int answer;
};

and following source file class.cpp

#include "class.hpp"
// nothing here

and following main source file main.cpp

#include <iostream>
#include "class.hpp"
int C::answer = 42;
int main()
{
    std::cout << "And the answer is " << C::answer << "." << std::endl;
}

Now, compile class.cpp -> class.obj, main.cpp -> main.obj, and link class.obj main.obj -> executable. It works as expected. But suppose, you came up with different project (anothermain.cpp), that will use same class.hpp.

#include "class.hpp"
int main()
{
    std::cout << "And the answer is " << C::answer << "." << std::endl;
}

Going through same compilation process results in link error

unresolved external symbol "public: static int C::answer"

So, to answer your question. It is possible. The linker does not care which object file contains definition for that value (as long as it's defined only once). However, I would not recommend it.

Upvotes: 1

Related Questions