Unusual behavior with C++ pointers (explanations?)

I'll just post the code and explain why I'm confused.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using namespace std;
#include <iostream>
#include <list>

class animal {
public:
	animal() {}
	virtual void Bark() {
		cout << "insert animal sound\n";
	}
};

class panda : public animal {
public:
	panda() : animal() {}
	virtual void 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.
Last edited on
Line 40: Did you mean ==?
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.
AGGGGGGGGG HAHAHAHA. I thought I was onto something big.
While we are on the topic thoughh,

I do have another question.

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.
Last edited on
Topic archived. No new replies allowed.