I am trying to code an efficient implementation of the following composite class:
class composite{ vector<base_class *> Vec;
My question is about the constructor and instance of the class, and in particular the Vec object. At this point, I am using a rather crude implementation described below. I am an implementation to be effective memory. I am pretty much new with C ++, so I'm not sure if I have an optimal solution here ...
I use polymorphism to store various derived classes in a vector, for example.
vector<base_class *> Vec1; Vec1.reserve(2); class1 * C1 = new class1(....); Vec1.push_back(C1); class2 * C2 = new class(....); Vec1.push_back(C2);
where class1 and class2 are derived classes of base_class. Then I pass Vec1 to the composite constructor as follows:
composite::composite(vector<base_class*> Vec1){ Vec.reserve(Vec1.size()); Vec.swap(Vec1);
I feel this is pretty memory efficient because Vec1 will be empty after building (its elements have been replaced with Vec). On the other hand, this seems rather wasteful, as I essentially copy Vec1 to Vec. Is there a better way for me to do this? Can I somehow insert the Vec1 vector into a composite? Thanks in advance!
c ++ polymorphism constructor vector std
Plamen
source share