I have
1- class A {int m;};
2- class B: public A
{float n;};
3- class C: public A
{string n;};
I store all instances of class A in
vector <class A*> myInstansesofA;
It is stored as a pointer because I dynamically create them according to some if statement
if (some condition)
{
A* newA = new B();
myInstancesofA.push_back(newA );
}
else
{
A* newA = new C();
myInstancesofA.push_back(newA );
}
Now I need to create an exact copy of the vector. With new set of pointers, but exact copy of the data.
Problem is in copying the data for each instance of A (which are actually B and C) to the new vector.
I tried the following but it doesn't work.
for (vector<A*>::const_iterator it = myInstancesofA.begin(); it != myInstancesofA.end(); ++it)
{
A* newA = new A(*(*it));
myInstancesofA.push_back(newA );
}
I suspect this error occurs because of "new A" invokes only the copy constructor for type A and does not invoke of B or C (I dubugged and found this was happening).
How can I solve this ?
I believe you cannot invoke the constructor like that, and there is no straight-forward way in C++ to do something similar (it is pretty straight-forward for language with Reflection, like Java and C#).
One way is to make use of prototype pattern
class A {
public:
virtual A* clone() {
return new A {...};
}
};
class B : public A {
public:
A* clone() override {
return new B {.........};
}
};
class C : public A {
public:
A* clone() override {
return new C {.........};
}
};
The object itself is responsible to create a clone of itself. Of course more thing to improve on the design but at least it gives you a taste of it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.