The original problem is flawed. dyanmic_cast won't help you here.
pabloist wrote: |
---|
I'm sure that there's some way to apply the properties of thief to Player...that is, to typecast Player as a thief. |
There isn't. Player is a 'beginner', it is not a 'thief'. You can't change the type of an object. Once you give it a type, that's it.
In your example, you solidify Player as a 'beginner'.
The examples I saw in the tutorial used pointers, but is that really necessary? |
Yes. Because the type of the pointer doesn't change (it will always be a 'beginner*'), but
what you point to can change (sort of). Through dynamic allocation, we can allocate different types.
Note that the "you can't change the type" rule still applies to the dynamic allocation approach. If we are pointing to a beginner and we want to change it so we're pointing to a thief, the only way is to
destroy the beginner and create a completely separate thief.
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
beginner* Player;
Player = new beginner; // Player points to a 'beginner'
// say we want to change that to point to a thief
beginner* temp = new thief(*Player); // create the new thief
// (using the copy ctor so as much data from 'Player' can be retained)
delete Player; // kill the original player
Player = temp; // and make Player point to our temp object (the thief)
// now Player points to a thief, even though it's still a 'beginner*' pointer.
// the magic of polymorphism!
|
Denis wrote: |
---|
If you need this cast usually it means bad design |
+1 @ this.
If you're downcasting, more than likely you're doing it wrong. Downcasting is actually quite rare in my experience.