G'day!
I was looking at the third Enginuity article, and he uses classes derived from his Task class, which I perfectly understand (the concept, that is), but later on he has a task manager (he calls his Kernel), which has std::lists of the Task base class, not any derived class. He did say that you you need inherit from the base Task class, and as he made two of the functions pure virtual, it's very obvious.
I tried to mimic this set up using std::list, and made up some simple classes, but it doesn't work as his is supposed to.
The source:
#include <list>
#include <iostream>
using namespace std;
class John {
public:
virtual void Write() {
cout << "John here!";
};
};
class Jeff : public John {
public:
virtual void Write() {
cout << "Jeff here!";
};
};
class Jerry : public John {
public:
virtual void Write() {
cout << "Jerry here!";
};
};
int main() {
list< John > myList;
John john;
Jerry jerry;
Jeff jeff;
myList.push_back(john);
myList.push_back(john);
myList.push_back(john);
myList.push_back(jeff);
myList.push_back(john);
int i = 0;
for (list< John >::iterator it = myList.begin(); it != myList.end(); it++) {
cout << "myList[" << i << "].Write();" << endl;
it->Write();
cout << endl;
i++;
}
return 0;
}
The output is as follows:
myList[0].Write();
John here!
myList[1].Write();
John here!
myList[2].Write();
John here!
myList[3].Write();
John here!
myList[4].Write();
John here!
The problem is, myList[3] is actually a Jeff, not a John, so shouldn't it print "Jeff here!" instead??
I did notice that when I hovered over Write() in it->Write() in the for-loop, it said "virtual void John::Write(void)" which makes me think that it->Write() is calling John::Write of jeff, not Jeff::Write, and I do remember something in my book about that... but I've lent that to my friend...
Anywho, can anyone explain this anomoly? (spelling?)