Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In C++ what is the correct way to filter a vector of polymorphic derived classes?

Here is an obviously simple example that compiles and runs.

#include <iostream>
#include <vector>

using namespace std;

class Shape {
    public:
    virtual double getArea() = 0;
};

class Circle : public Shape {
    public:
    double getArea() {return 3.14;}
};

class Rectangle : public Shape {
    public:
    double getArea() {return 42.0;}
};

int main() {

    vector<Shape*> shapes = {new Circle(), new Rectangle()};

    for (Shape* s : shapes) { cout << s->getArea() << endl;}

    return 0;
}

The result is that it will print every Shape in the vector.

What I do not know how to do is to filter the vector by derived class type. For example, how to iterate over the vector and only do something for each Circle?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank You

>Solution :

First of all, if you want to treat Circle’s differently from other shapes, you should consider simply storing them separately from other shapes.

But sometimes you want to do the same things for all shapes most of the time, and something special for Circles some of the time.

In such a case, you’d do a dynamic down-cast to get from a pointer to Shape to pointer to Circle. If the Shape it points to isn’t a circle, this will fail and yield a null pointer.


class Circle : public Shape {
    public:
    double getArea() {return 3.14;}
    void circlesOnly() { std::cout << "Whee! I'm a circle!\n"; }
};


vector<Shape*> shapes = {new Circle(), new Rectangle()};

for (Shape *shape : shapes) {
    if (Circle *c = dynamic_cast<Circle *>(shape); c != nullptr)
        c->circlesOnly();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading