user1706918
user1706918

Reputation:

C++ copies of objects with abstract class pointers

Consider the Container class, which basically stores a vector of unique_ptrs 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?

Upvotes: 4

Views: 1961

Answers (1)

1201ProgramAlarm
1201ProgramAlarm

Reputation: 32732

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.

Upvotes: 4

Related Questions