So everyone knows that global variables are bad (most of the time), but is it ok to put a variable in a class to acces to it indirectly from any part of the program?
> So everyone 'knows' that global variables are VERY bad ..
Do people who say that really 'know'?
It is not global variables per se, but variables with global visibility and access that results in tight coupling.
Global variables with visibility restricted to a single translation unit is a staple of well designed C/C++ software.
1 2 3 4 5 6 7
// a.h
class A
{
// ...
private: staticint v ; // progrmmatically visible to the entire program
// ...
};
1 2 3 4 5
//a.cc
int A::v = 45 ;
// A implementation
1 2 3 4 5 6 7
// better_a.h
class better_A
{
// ...
// move 'v' to the implementation file with internal linkage
// ...
};
1 2 3 4 5 6 7 8 9 10
// better_a.cc
namespace
{
int v = 45 ; // visible and accessible to the implementation of better_a
// progrmmatically invisible to the rest of the program
// in C, this would be: static int v = 45 ; at global scope
}
// better_a implementation
// the implementation can access 'v'
I know that in real life people use functions to set and use variables inside classes instead of making them public, is it ok to put the score of my game in a class at the starting of the program to use it on all the functions I want? That's why I ask this.
> is it ok to put the score of my game in a class to use it on all the functions I want?
Yes.
Provide a narrow and a (restricted) wide interface, perhaps. Something like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// score_keeper.h
class score_keeper
{
// everyone can read the score
public: staticint score() ;
// only some can modify the score
private: staticvoid score( int new_value ) ;
// these classes are allowed to modify the score
friendclass game ;
friendclass another_class_allowed_to_modify_the_score ;
};
The advantage of JLBorges approach is first and foremost that you don't even have to create a Score object, because it uses static members.
This means that you won't have to pass the Score object around all the time, if you're in a befriended class, you can simply get and set the score through score_keeper::score().
Please do correct me if I'm wrong here anyone- no expert myself.
Static member data and friend classes are slightly more advanced OOP though, so don't worry that you didn't think of it.
Hope that helps, let us know if you have any further questions.