c++ - What is the best way to handle a collection of derived objects in a derived class -
imagine have class 'basea' contains collection of items 'itema'. want extend 'basea' add capabilities, derive 'deriveda' 'basea'. 1 characteristic of 'deriveda' has handle more sophisticated 'deriveditema' items instead of 'itema' ones.
class basea { protected: vector<itema> x; void m1(int i) { x.m1(i); } }; class itema { protected: void m1(int i) { ... } }; class deriveditema : public itema { void m2(int i) { ... } };
now handle of sort:
class deriveda : public basea { vector<deriveditema> x; void m2(int i) { x[i].m2(); } };
i.e. have derived class handle derived items. above definition of x incorrect clashes 1 in basea. idea want able reuse methods in basea handle x long deal itema elements , have extended methods in deriveda handle intricacies of deriveditema type of data
any suggestion? current thoughts in lines of defining new datatype x (vectorofitema instance) , derive vectorofderiveditema. wonder if there simpler / better solution.
thanks
i believe need have pointers in vectors in order handle this. i'm little confused value pass m1 , m2 since appears index, here's guess:
class basea { protected: vector<itema*> x; void m1(int i) { x[i]->m1(i); } }; class itema { protected: void m1(int i) { ... } }; class deriveditema : public itema { void m2(int i) { ... } }; class deriveda : public basea { vector<deriveditema*> y; //don't shadow base class vector! void m2(int i) { y[i]->m2(i); } };
then, when add item in deriveda, add both x , y. way basea can it's thing pointer in x , deriveda can thing on pointer in y.
edit: you'll need provide virtual method adding items otherwise might things added basea.x don't added deriveda.y.
Comments
Post a Comment