Parallel class hierarchies and downcasting


I have a simple GUI app working, with my own custom subclass of Button embedded in another Component subclass. I want to make the parent Component a button listener, and this requires that I inherit from Button::Listener and override this:

void buttonClicked(Button *button);

But to actually get at the custom fields and methods of my button subclass I have to manually downcast in the implementation, like this:

StepButton *sb = static_cast<StepButton *>(button);

This seems hacky and potentially type unsafe. Is there a better way to handle this?


you shouldn’t really use static_cast there, but a dynamic_cast would be fine. Just check it for null-ness before using it.