I have a parent class "base" and another class "derived" that inherits from "base".
"derived" has 1 method cH1.
if I do this:
base* b = new derived();
And I want to be able to do this:
b->cH1();
Obviously I can't and there are 2 solutions:
- Either declare cH1 as pure virtual in base.
or do this:
dynamic_cast<derived*>(b)->cH1();
Which one is a better practice?
First, in order to use
dynamic_cast
,base
must have at least one virtual function.Second, use of
dynamic_cast
is usually a sign of a design mistake. Ifderived
is truly a child ofbase
, then aderived
object should be able to stand in wherever abase
object is expected, and that usually means thatbase
has virtual functions, either pure virtual or not, and thatderived
overrides some or all of them.Without knowing what
cH1
does, though, it's impossible to recommend an approach.If
cH1
method semantically applies tobase
, then make it abase
's method. Else, leavecH1
toderived
, and usedynamic_cast
. I think the semantics of your classes should drive your choice.For example, if you have a base class
Vehicle
and derived classesCar
,Motorbike
, andAircraft
, a method likeTakeOff()
has a semantics compatible withAircraft
but not withCar
orMotorbike
, so you may want to makeTakeOff()
anAircraft
method, not aVehicle
method.dynamic_cast
is cleaner and more flexible, but a bit slower.Remember when you use
dynamic_cast
to check the returned pointer for NULL.