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?
If
cH1method semantically applies tobase, then make it abase‘s method.Else, leave
cH1toderived, and usedynamic_cast.I think the semantics of your classes should drive your choice.
For example, if you have a base class
Vehicleand derived classesCar,Motorbike, andAircraft, a method likeTakeOff()has a semantics compatible withAircraftbut not withCarorMotorbike, so you may want to makeTakeOff()anAircraftmethod, not aVehiclemethod.