You avoid this error by being more careful in your class design in the first place.
Yes, you can use dynamic_cast
or static_cast
to cast a Base
pointer to a Derived
pointer if the types are related, as they are here. But let's think about this.
Q: Why do you use polymorphism?
A: To provide different behaviour for similar operations, where the behaviour is selected at run-time.
Polymorphism is used to abstract away the implementation of an operation from the provision of that operation. All Shape
s for example have a number of sides. How many sides depends on the actual shape, but we shouldn't have to know what kind of Shape
something is in order to ask it how many sides it has. We should be able to just ask it.
Q: Why do you typically need to use dynamic_cast
?
A: Because the base pointer doesn't provide the facilities you need.
If we shouldn't have to care what kind of Shape
some object is in order to carry out the operations we need on it, then why would the Shape
interface ever not provide whatever facilities we need?
This happens when we've made a mistake in designing something. Either Shape
didn't have enough or the right kinds of facilities in it, or some particular Shape
subclass is trying to do more than it should.
That's what you've done here. If it doesn't make sense for Parent
to have a (public
) bar()
method on it, then it shouldn't make sense for Child
to have it either. If it does make sense for Child
to have a bar
method on it, then Child
isn't really a Parent
, is it?
Maybe bar
should be a method in some other class.