typecasting from a base to a derived class

I'm a little confused with type casting.

If I do something like

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class beginner
{
// constructor, member functions, etc
};

class thief : public beginner
{
// constructor, member functions, etc
};

int main()
{
beginner Player;

return 0;
}


I'm sure that there's some way to apply the properties of thief to Player...that is, to typecast Player as a thief.

I tried using static_cast because, from what I can understand, it can be used to cast to a derived class. Trying static_cast<thief>(Player); gave me:

error: no matching function for call to 'thief::thief(beginner&)'


The examples I saw in the tutorial used pointers, but is that really necessary?



1. You need to use dynamic_cast.
2. If you need this cast usually it means bad design
Okay then, good to know. Why does it mean bad design exactly?
Because you should avoid any cast.
Alright then..
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.
Okay, thank you for the more indepth explanation :) I'm only writing this to experiment with what I'm learning from the tutorial, so it's good to know what I should/shouldn't be doing.
Topic archived. No new replies allowed.