Pointers and polymorphism?

Hi, I feel very confused right now:


I think I'm really rusty right now after summer... What am I thinking wrongly here? I thought the whole point of inheritence and pointers was for this to work? (the code below is obviously shortened and does not represents my whole program)

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
Troll* troll = Troll::createTroll();
cout << typeid(troll).name(); //type is Troll* 
storeClasses("troll", troll);
cout << typeid(getClass("troll")).name(); //prints Character* 



Troll.h:
class Troll : public Character {
   static Troll* createTroll();
}; 

//edit: just want to mention that the superclass, Character, does feature virtual functions


Other.h
class OtherClass[
 unordered_map<string , Character*>chars;
 void storeClasses(string key, Character* ch){
    chars[key] = ch; 
 }
 Character* getClass(string key){
   return chars[key];
 }

}
Last edited on
Err, just to clarify in case it's not clear: I was expecting the "getClass("troll") to retrieve a pointer to a Troll instance and not a Character?
The function getClass() returns a an object of type Character*. It's not derived from anything, it's not even a class; so typeid is correct.

If you want to see it say Troll, get to that object first: typeid(*holder.getClass("troll")).name()
'chars' stores pointers to Character, so when you return an element of the map its type is Character*.

A simplified explanation of polymorphism:
The object's actual type is Troll, but since Troll inherits from Character it contains all the parts of Character, making it also a valid Character object. Therefore that object can be pointed to by a Character*.

The answer to your question is the first sentence, but I'm not sure if it's clear enough. I'll try to help you understand if you have doubts.

By the way, cout << typeid(*getClass("troll")).name() should output "Troll"
Last edited on
A simplified explanation of polymorphism:
The object's actual type is Troll, but since Troll inherits from Character it contains all the parts of Character, making it also a valid Character object. Therefore that object can be pointed to by a Character*.


Yes that's also why I was storing the troll in the character* container, however for some reason I was under the impression it was supposed to return a Troll*... Considering how a parent don't know anything about its derived classes that's kinda of an odd thought I guess...

I think something is wrong with my program since my program crashes when it dynamically cast a character* from that map into a Troll* so I was worried there for a while that my design was completely crazy but after all this, I'm sure there is something spooky going on in my code instead!


Thanks both of ya!

Topic archived. No new replies allowed.