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?
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();
}