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
for (list<B>::iterator it = list_of_B.begin(); it != list_of_B.end(); ++it) {
(*it).onlyBFoo();
}
for (list<C>::iterator it = list_of_C.begin(); it != list_of_C.end(); ++it) {
(*it).foo();
}
//This part I am not sure about
for (list<A>::iterator it = list_of_all.begin(); it != list_of_all.end(); ++it) {
(*it).foo();
}
To output:
I am B!
I am B!
I am B!
I am C!
I am C!
I am C!
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.
Basically, sometimes I want to only loop the Bs and Cs so that I can use their methods, but sometimes I want to loop all of them so that I can use the same method from each i.e. iterate the As, then the Bs, then the Cs all in one loop.
I thought of creating a separate list (like the code above) containing everything, but it would create lots of unnecessary maintenance, as I will be adding and removing every object from 2 lists instead of one.