I am trying to port some classes from one big piece of C++ codes from another team to another piece of codes in our team.
Originally, inside the old program, there was a global variable "rawdata" which can be used by everyone. But when porting some classes, my senior told me to put "rawdata" into the major class, and use its constructor to initialize "rawdata". (I guess he wants as few global variables as possible)
However, my current situation is that, I don't know how to make other classes to access "rawdata" without passing an object. For example,
class majorpart() {
int rawdata;
majorpart(int input) {rawdata = input;};
}
class otherpart() {
if(rawdate==0) // Here we don't want an object of class majorpart
do something; // Is it possible for us to directly access rawdata?
}
I am kind of new to C++. Could anyone give me some suggestions? Thanks
Based on your source code an example with a singleton-class:
class rawdata {
private:
static int *_instance;
rawdata() { }
public:
static const int *instance() {
if (_instance) return _instance;
else return (_instance = new int(10));
}
};
class majorpart {
majorpart() { };
};
void doSomething() {
}
class otherpart {
void someFunction() {
if (rawdata::instance()) // Here we don't want an object of class majorpart
doSomething(); // Is it possible for us to directly access rawdata?
}
};
The idea is to wrap the rawdata
field with a class to control how it is initialized, accessed, etc.
You mentioned in a comment to immiao's answer, that you would need to fiddle around with macros. You'd need to do this anyway. It doesn't matter if it is in majorpart
as field, static field or in rawdata
as a singleton-wrapper.