Is it bad to have objects pass themselves to new objects?
My app has a bunch of different data types, and a bunch of different
graph types that can draw the data. This is a pretty much a 1:1
mapping -- one graph type for each data type. One way I've heard of
handling this situation is to have a factory. The factory would take
in the data and put out the appropriate graphs. I thought, "That seems
unnecessary, why not just have the data types know what graph type
they correspond to..." So something like this:
class Graph {};
class GraphA {
public:
GraphA(dataA* data) : _data(data) {}
void Render() { /* Do some stuff with data to make a pretty graph
*/ }
private:
dataA* _data;
};
class data {
public:
virtual Graph* BuildGraph() = 0;
};
class dataA : public data {
public:
virtual Graph* BuildGraph() { return new GraphA(this); }
};
Now instead of plugging the data into a factory to make a graph you
just do data->BuildGraph() and it makes the graph. My question is: is
this a bad idea? Is there some reason why a factory is preferable?
One problem I noticed is that if later GraphA and dataA are made
templates, then their declaration and source both goes in their
headers, and you end up with circular #include's because dataA needs
to know about GraphA in order to instantiate it, and GraphA needs to
know about dataA in order to plot it. But maybe there are other perils?
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]