Search code examples
c++classloopsinheritancesuperclass

Iterate over different objects


I would like to iterate over different objects that all inhereit from the same superclass. That means I have a superclass like this:

class fruit
{
   public: 
      fruit()
      {
      }
};

And I have subclasses like this, which define the objects that are used in my code:

class apple: public fruit
{
   public: 
      apple()
      {
      }
};

class banana: public fruit
{
   public: 
      banana()
      {
      }
};

Now I want to iterate over all fruits (apples, bananas):

for ( first fuit; last fruit; next fruit )
{
    // do something, no matter if apple or banana
}

But how should I do this since apples and bananas are different class types, but they share the same superclass. This is why I think, that there has to be an elegant way to do it.


Solution

  • C++ doesn't have any kind of built-in object registry where you can get access to every existing object of a particular type. However, C++ has multiple container types that can be used to store multiple objects in a variety of different data structures.

    Since the objects you are storing are of different types but with a common base type, you need to use pointers or references to achieve polymorphic behavior and avoid object slicing.

    For example, you can use a vector of std::unique_ptr objects.

    std::vector<std::unique_ptr<fruit>> fruits;
    
    fruits.emplace_back(new apple);
    fruits.emplace_back(new banana);
    
    for (auto &fruit : fruits) {
        // fruit is a reference to the unique_ptr holding the pointer-to-fruit. Use
        // the "indirect access to member" operator -> to access members of the
        // pointed-to object:
    
        fruit->some_method();
    }
    

    The advantage of using this approach (vector of unique_ptr objects) is that your apple and banana objects are automatically destroyed when the vector is. Otherwise, you have to delete them manually, and that is a very error-prone approach.