Search code examples
c++inheritanceiteratorabstract-class

How to define Iterators for an abstract class in C++


I'm working on a C++ project where I have an abstract class called Aggregate, which represents a container for another abstract class called Primitive.

I want to be able to iterate through an Aggregate, without worrying with the details of how the Primitive objects are actually stored.

Since I'm not really proficient with C++, I have two questions:

  • First, is it even possible to do something like this?
  • Second, what exactly should my Aggregate class and its derived classes do in order for this to work?

Any explanation/references are very much appreciated.


Solution

    • First, is it even possible to do something like this?
    • Second, what exactly should my Aggregate class and its derived classes do in order for this to work?

    Yes, you "simply" add to Aggregate two virtual functions returning a begin() and an end() iterator.

    struct Aggregate
    {
        struct iterator { /* ... */ };
        virtual ~Aggregate() {}
        virtual iterator begin() { return {}; }
        virtual iterator end() { return begin(); }
    };
    

    You can then use range for loops and algorithms from the Standard Library for "free":

    for (auto& p : aggregate) {
        p.value = 0;
    }
    
    std::copy(aggregate.begin(), aggregate.end(), aggregate_copy.begin());
    

    You'd need some boilerplate code to implement a working iterator though, but you'll manage with a good Google search.

    Working demo