Sign in to follow this  

Question about inheritance behaviour

This topic is 3724 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm writing a little win32 API wrapper in C++ and I got a question. (<-- means inherits from) Component <-- Button Component <-- Button <-- Checkbox Pseudo code:
map<ID, Component> map

map[someID] = (button part of a checkbox)

...

checkbox c = dynamic_cast<Checkbox>( map[someID] )



The reason that only the button part of the checkbox is stored in the map is basically becouse the Button constructor alredy creates the window and register the component for button objects. I know for sure that the object beeing downcasted is a checkbox object, and it seems to work so far but Im wondering if downcasting like this is considered undefined behaviour or some other troll that could blow up in my face later on? Thanks edit: I forgot to say that the map stores pointers. Sorry. The info I have found about this that is at least remotely relevant to my problem indicates that my downcast is just fine for pointers and references, and that I can use static_cast as well to avoid RTTI. If you guys dont have anything to add Ill go with it. [Edited by - spoofcrow on September 29, 2007 11:03:00 PM]

Share this post


Link to post
Share on other sites
You should definitely work to eliminate all casts in your code. Casts are hacks to cover up defects (either in the language, legacy code, or poorly written new code).

You should switch your code around so that you can avoid the cast. For example when you create the textbox retain a pointer or reference to it and pass that around. Or have it register itself in multiple containers.

In my game I have two types of Units, Squads and Heroes. When a Hero is constructed it adds a pointer itself to a container containing all Units, and another container just containing the Heroes. Then if I want to do something for every unit I access them through the Unit container, and if I just want the Heroes I do it through the Hero container. If I want to do something to every Unit but I want Heroes and Squads to do it differently I do it through the Unit container but I make the function that I am calling virtual.

Share this post


Link to post
Share on other sites

This topic is 3724 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this