Salmonstrikes Salmonstrikes - 1 year ago 59
C++ Question

C++ copies of objects with abstract class pointers

Consider the

class, which basically stores a vector of
s of
objects and can perform some computations on them.

class Container
std::vector<std::unique_ptr<Box> > boxes_;
Container(std::vector<std::unique_ptr<Box> > &&boxes): boxes_(std::move(boxes)){}
double TotalVolume() { /* Iterate over this->boxes_ and sum */ }

is an abstract class that has a pure virtual method such as
double Box::Volume()

Now, suppose that I instantiate a container in the main program as:

std::vector<std::unique_ptr<Box> > x;
x.push_back(std::move(std::unique_ptr<Box>(new SquareBox(1.0)));
x.push_back(std::move(std::unique_ptr<Box>(new RectangularBox(1.0, 2.0, 3.0)));
Container c(x);

How do I make copies of
? I would like a function that makes copies of the underlying
object in
, but I think it's hard to do this with base classes?

Answer Source

One way to make your copies is to have a "Copy" virtual method in your base class. This method would create a copy of the current object and return a (unique) pointer to it. If there are any contained pointers within the class, they'd need new copies created as well (a deep copy).

Other approaches exist. For instance, you could test each object in the vector to determine its type (using dynamic_cast), but this is ugly, inefficient, and very error prone.