Hello everyone,
I just joined this forum and I already have a few questions I'd like to ask.
First of all, I want to collect an undefined number of objects of miscellaneous classes in an STL vector. All these classes inherit from some abstract base class:
Code:
class Base { ... };
Since one cannot instantiate a base class object the vector needs to be defined this way:
Code:
std::vector<Base*> allobjects;
Btw.: all objects are created by factory functions, which create the class objects and return them via pointer.
Of course I'll want to make (deep) copies of that vector at some point during run time. Since now I have to manually create those deep copies I would make use of the new operator and pass the old objects to the copy constructor. But there's the problem: I cannot do that, because I don't know the real type of the objects. So, my solution was to declare a purely virtual factory method to create a copy of "this" and return it via pointer. In every class, that inherits from "Base", the method was implemented according to the class hierarchy:
Code:
class Base
{
...
public:
virtual Base* createDeepCopy(void) const = 0;
protected:
Base(const Base& to_copy);
private:
Base& operator=(const Base& rhs); // no implementation, not supposed to be called
...
};
class AChild : public Base
{
...
public:
virtual AChild* createDeepCopy(void) const
{
AChild* tmp = new AChild(*this);
// copying not inherited members
return tmp;
}
...
};
So, my first question would be: am I right with my assumptions above or is there a better solution for this?
Now it gets even worse: I would like to have some child class, whose instances must not be copied!
Code:
class Base
{
// as above
};
class AChild : public Base
{
// as above
};
class BChild : public AChild // must not be copied!!!
{
...
};
Of course objects of type "BChild" will never be put into the mentioned vector -- this is assured in the program.
All I came up for a solution was this:
Code:
class BChild : public AChild
{
...
private:
virtual BChild* createDeepCopy(void) const
{
// no real implementation
return NULL;
}
...
};
Second question: Is there a better way to implement this?
Thanks in advance for your comments and hints.
Regards
Sigi