Salmonstrikes Salmonstrikes - 1 month ago 7
C++ Question

C++ copies of objects with abstract class pointers

Consider the

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

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


Here,
Box
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
c
? I would like a function that makes copies of the underlying
Box
object in
boxes_
, but I think it's hard to do this with base classes?

Answer

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.

Comments