I have several complex classes, that are constructed using separate creator classes that inherits from the class to create.
One example might be a graph that is constructed from unordered data.
class Graph{
//....
public:
void showData();
protected:
std::vector<std::pair<int,int> > mConnectedData;
}
class GraphCreator:private Graph{
public:
//...
void construct();
private:
std::map<double,int> mSomeHelperContainer;
//...
}
For the construction I need many helper functions and also helper data, which I put in another class GraphCreator. Since many graph related functions are also necessary and since I need the data of the graph at any case I use private inheritance.
Since this is by no means the famous is-a relation and since private inheritance is generally considered a hint for bad design I have some doubts:
Is this a good Idea and one appropriate way to design a factory or are there some major drawbacks that I have no thought about ?
What would be a better way of designing a such a factory ?
Edit:
Thanks for the answers so far !
Some additional information to make the reason for the currently used approach clearer.
I cannot use a static creation method (far too many state variables in the Creator) and I have another constraint:
I want to provide the Graph independent from the creator (e.g together with a read from file method) in a library to other people.
Those should not have to care about the creator. Therefore I am also a little unsure about friend usage, since it adds code inside the Graph class.
It is not a good way (inheritance from anything with data rarely is).
The traditional approach is to either:
GraphCreatorafriendofGraphstaticBuildmethod inGraph(directly)The decision mainly depends on whether you need the “factory” to be stateful. A
classis used to represent state, which a method cannot do.classto store it, and thusGraphCreatoris your best bet.staticmethod is much more lightweight.If you are undecided, pick the easiest (
staticmethod) and see how far it goes 🙂