Where should I initialize member variables?

I'm still learning C++ and from time to time I write code to get better understanding of the language. What is causing me confusion is how to initialize variables?

If I have a variable that needs to be accessed by multiple functions. I define the variable in the .h file (let's call it neededEverywhere). When I try to initialize the variable in the constructor as neededEverywhere = 0; I get an error: Undeclared variable.

The only way to get around this is declare the variable as int neededEverywhere; after the end of all #include(s) and before the beginning of the constructor and then be able to initialize neededEverywhere inside the constructor, and use it in all other functions.

Is this the way to initialize variables in C++?

If the variable was a constant I know I can initialize it in the .h file but it's not and I don't want to break advised best practices.
Last edited on
You need to show some code that illustrates your question. If the variable in question is a class member variable then it should probably be initialized in the class constructor.

If you're talking about a global variable, then you should strive to eliminate this variable, and instead pass the variable to the functions that require it as a parameter.


Topic archived. No new replies allowed.