c++ - Invoke the copy construction of a derived class from a pointer to the base class? -
i have
1- class {int m;}; 2- class b: public {float n;}; 3- class c: public {string n;}; i store instances of class in
vector <class a*> myinstansesofa; it stored pointer because dynamically create them according if statement
if (some condition) {       a* newa = new b();       myinstancesofa.push_back(newa ); } else {       a* newa = new c();       myinstancesofa.push_back(newa ); } now need create exact copy of vector. new set of pointers, exact copy of data.
problem in copying data each instance of (which b , c) new vector.
i tried following doesn't work.
for (vector<a*>::const_iterator = myinstancesofa.begin(); != myinstancesofa.end(); ++it)     {         a* newa = new a(*(*it));         myinstancesofa.push_back(newa );     } i suspect error occurs because of "new a" invokes copy constructor type , not invoke of b or c (i dubugged , found happening).
how can solve ?
i believe cannot invoke constructor that, , there no straight-forward way in c++ similar (it pretty straight-forward language reflection, java , c#).
one way make use of prototype pattern
class { public:     virtual a* clone() {         return new {...};     } };  class b : public { public:     a* clone() override {         return new b {.........};     } };  class c : public { public:     a* clone() override {         return new c {.........};     } }; the object responsible create clone of itself. of course more thing improve on design @ least gives taste of it.
Comments
Post a Comment