Say I have a superclass that, when it initializes, wants to run some code that relies on a whole bunch of class variables that may or may not be overridden by a subclass in its constructor.
What's the accepted, clean way to code that?
I feel like I'm having a brain fart; this should be a standard, beginner usage of inheritance, but I can't figure it out.
e.g. say I have a superclass that represents a vehicle, and when it starts, I want to do a whole bunch of code where it processes, say, the load per axle or something (doesn't matter) but that code uses as inputs a bunch of parameters that exist for all vehicles (and thus exist in the superclass), say weight, length, numwheels, numaxles, maybe even complicated data structures defining how many wheels per axle, etc.).
The various subclasses (sportscar, bigrig, motorcycle), want to set the weight, length, numwheels, numaxles, etc. before the superclass does its processing.
Super::Super() {
Process(var1_,var2_,var3_,var4_, ...);
}
Sub1::Sub1(): Super() {
var1_ = <some math>;
var2_ = <some math>;
...
}
doesn't work because the superclass Process() runs before the vars get set by the subclass. Right?
Super::Super(float var1, WackyDatastructureDef var2, int var3, WackyStruct2 var4, ...),
var1_(var1), var2_(var2), var3_(var3), ............... {
Process(var1_,var2_,var3_,var4_, ...);
}
Sub1::Sub1(): Super(<some math>, <some math>, <some math>, <some math>, ......) {
....
}
looks horrible for obvious reasons. Also, it looks like a pain if I only need to override 2 out of the 20 default variable values.
Super::Super() {}
void Super::Init() {
Process(var1_, var2_, var3_, var4_ ...... );
}
Sub1::Sub1(): Super() {
var1_ = <some math>;
var2_ = <some math>;
...
Init();
}
looks the cleanest but I don't like it... it's weird to have to remember to call Init() at the end of all my subclass constructors. What if another programmer wants to subclass off my superclass and doesn't know my magic rule?
What's the right way to do this?