A global static class to contain data
c++, class, oop
Solution
So just have it as a `static` member:
//Globals.h
class Globals
{
public:
static float scalingFactor;
}
initialize it in a single implementation file:
//Globals.cpp
#include "Globals.h"
float Globals::scalingFactor = 42.0;
and use the scope resolution operator to access it:
float x = Globals::scalingFactor;
I've tried using namespaces but namespaces do not allow member variables
You haven't used namespaces correctly. The following should work:
declaration in header:
namespace Globals
{
extern float scalingFactor;
}
and the definition:
//Globals.cpp
namespace Globals
{
float scalingFactor = 42.0;
}
Problem
I want to have a static class that would hold different kinds of data (like directories, values, etc.). I've tried using `namespace`s but `namespace`s do not allow member variables, which I need to hold data (correct me if I'm wrong, though). What I'm trying to do is save some constants for the whole program to use - `scalingFactor` and `screenSize` to name a few. Then, I want those data to be shared by all parts of the program. Something like this: In Foo.cpp: ``` void doSomething( float p_Float ) { printf( "Scaled Float is %.2f", p_Float * Globals.scalingFactor ); } ``` In Goo.cpp: ``` void doSomethingElse( ) { printf( "Scaling Factor is %.2f", Globals.scalingFactor ); } ``` The `scalingFactor` should refer to the same value, the value of `scalingFactor` in the global static class `Globals`. Thanks in advance. EDIT: I also need to use global functions, does it work the same as variables in this question?