usingnamespace std;
#include <iostream>
#include <list>
class animal {
public:
animal() {}
virtualvoid Bark() {
cout << "insert animal sound\n";
}
};
class panda : public animal {
public:
panda() : animal() {}
virtualvoid Bark() {
cout << "nom nom nom\n";
}
};
int main() {
list<animal*> animalList;
list<panda*> pandaList;
panda* myPandaPtr = new panda;
panda* golden = new panda;
panda* shoota = new panda;
animalList.push_back(myPandaPtr);
animalList.push_back(golden);
animalList.push_back(shoota);
list<animal*>::iterator it = animalList.begin();
for(it; it != animalList.end(); it++) {
if (*it = shoota) {
cout << "Yep!\n";
}
}
char wait;
cin >> wait;
return 0;
}
I've created 3 UNIQUE panda pointers. When I output this code, I get the following results,
yep!
yep!
yep!
Huh? Shouldn't it make more sense to only get
yep!
Because only one pointer in the list should have the same address as the pointer shoota.
Does this have something to do with generic programming (Note how the list holds animals but the pointers are all pandas)? Any respones/comments appreciated. I might just be making a dumb error.
When you do '=', you're making an assignment. As long as that assignment is done without error, it equates to 'true' inside that if statement. You're re-assigning that pointer 3 times.
Check out what @helios said for a solution.
If I compare base class pointer animal "Shoota" with derived class pointer "Shoota", should I always return true?
I read somewhere else that pointers are not all the same size, so I thought maybe "animal* shoota" and "panda* shoota are not necessarily the same thing.
Well, you know, I cannot confidently answer that. I won't answer that, potentially mix something up, and then confuse you.
What I CAN tell you is that a pointer to an base class can also point to a derived class. That is because that derived class is guaranteed to have everything that the base class has.
If I have an base class, say Pet, and a derived class, Dog. You can have a Pet pointer pointing to a dog, because it IS an animal. You know that you are pointing to something that is at least an animal.
That does not go the other way. You can't make a Dog pointer point to an animal. You cannot assume that animal is a dog - it could be a bird.