I have the following problem (just learning OOP style C++): I have 3 classes:
- app
- objectManager
- object
The app class sets up startup variables and creates an instance of objectManager. It tells objectManager to load values from different files and to precalculate some data in a vector what will be required for each object.
My problem is the following: I would like to use a precalculated vector accessable for each object. I don’t understand how can I possibly access this variable from the objects, as they know absolutely nothing about the manager’s instance.
I’ve read about singletons but I have no idea how should I implement it.
I’ve read about static data members but AFAIK it seems that I still have to somehow connect to the objectManager instance, so it doesn’t help me.
I’ve tried global variables (I know…), but ended up with compiling errors.
I’ve tried to put static variables outside of a class definition in objectManager.h (is it a global case?), and I ended up with something strange:
I can access the variables from all parts of the program what includes objectManager.h, but it’s value is different/uninitialized in different classes.
objectManager.h
#pragma once
#include "Object.h"
static int xxxtest;
class objectManager
{
objectManager.cpp
xxxtest = 123456;
cout << xxxtest << endl;
-> 123456
while in object.cpp or app.cpp (after)
cout << xxxtest << endl;
-> 0
Can you explain to me what is happening here?
Can you recommend me a simple and clean way of organizing such a program, while making a precalculated variable accessable to other parts of the program?
Static class variables are in fact the solution.
Static variables in classes need to be declared in the CPP file, right after the include.
Header:
CPP:
Do that, and all Object instances have access to the static variable (if it’s private) and all members of the entire Program can access it (if it’s public) by stating:
I hope this helps shed some light.
Ah yeah, I used the code from http://de.wikibooks.org/wiki/C++-Programmierung:_Statische_Elemente_in_Klassen (Page is in German) as Reference.
To get back to your problem, that would mean:
Header:
CPP: