I have a C++ component that contains important data that needed from various other components in my program.
The component might contain its own task or not. But in either case it will also hold the data in structs or classes.
The other components that will include the component in question might not need all the data from it.
For example:
We have a component options
that contain contain some options/configuration for other components.
Some options might not needed from one component.
The question is whether the module options
should be a class and make it public with extern
keyword in the header file or just use plain free functions (getters)?
If options
is an object. It will be only one object. There's no need for a second object to be created. So it's gonna be either a singleton or just a public object in the cpp
file passed global with extern
keyword in the header.
Editing my question to clarify a couple of things regarding the two possible solutions.
A class:
class options
{
int getOption1();
int getOption2();
char getOption3();
float getOption4();
char * getOption5();
}
Free functions:
namespace options
{
int getOption1();
int getOption2();
char getOption3();
float getOption4();
char * getOption5();
}
Best Answer
So, you have to decide between a singleton and a bunch of free functions in a namespace, with some dedicated global state either way?
First, why do you want a singleton?
If it is just to ensure they share the state, consider extracting it into namespace-level TU-internal variables, and make any functions you want static. No need to muck around with singletons, which are ill regarded due to blatant over- and mis-use, aside from mis-implementation.
Next, why a class at all?
This is not Java, you can have free functions and global state outside classes, perfectly hidden from the outside unless external linkage is requested. It has the advantage of easier extensibility, and unless you need to provide a specific interface (for static injection with templates or dynamic injection with inheritance), there is no downside.
This is actually the preferred way, absent reason to do otherwise.