I have 3 classes, 2 inheriting from the other like so:
class A {
public:
virtual void foo() {cout << "I am A!" << endl;}
};
class B : public A {
public:
void foo() {cout << "B pretending to be A." << endl}
void onlyBFoo() {cout << "I am B!" << endl}
};
class C : public A {
public:
void foo() {cout << "C pretending to be A." << endl}
void onlyCFoo() {cout << "I am C!" << endl}
};
What I want to do is something like this:
list<A*> list_of_A;
list<B*> list_of_B;
list<C*> list_of_C;
//put three of each class in their respective list
cout << "First loop:" << endl;
for (list<B>::iterator it = list_of_B.begin(); it != list_of_B.end(); ++it) {
(*it)->onlyBFoo();
}
cout << "Second loop:" << endl;
for (list<C>::iterator it = list_of_C.begin(); it != list_of_C.end(); ++it) {
(*it)->onlyCFoo();
}
//This part I am not sure about
cout << "Third loop:" << endl;
for (Iterate all 3 loops i.e. *it points to As, then Bs then Cs) {
(*it)->foo();
}
To output:
First loop:
I am B!
I am B!
I am B!
Second loop:
I am C!
I am C!
I am C!
Third loop:
I am A!
I am A!
I am A!
B pretending to be A.
B pretending to be A.
B pretending to be A.
C pretending to be A.
C pretending to be A.
C pretending to be A.
i.e. sometimes I want to only iterate the B objects, but sometimes I want to iterate all the objects.
One solution would be to store them all in a list, however I want to be able to loop through them in order of type i.e. the As then the Bs then the Cs.
Another suggested solution was to use iterators or iterator_adapters, however I have never used them before and can't find a simple example to help me get started with them.