I have two subclasess inheriting from the same abstract superclass. There is a common operation to all subclasses which depends on several attributes. Let me explain with an example:
Say this is superclass A (A is abstract):
class superClass
{
int valueA;
int valueB;
float* array;
public superClass(){
array[valueA + valueB]
}
virtual foo(){
}
}
And these are my subclasses:
class firstSubClass: superClass
{
public firstSubClass():superClass(), valueA(100),valueB(2){
}
foo(){
}
}
class secondSubClass: superClass
{
public secondSubClass():superClass(), valueA(50),valueB(3){
}
foo(){
}
}
Will the array be properly initialized? Which translates to, is the subclass constructor called before the superClass one, or is it the other way around?
Is there a way to make the initialization behavior common to both subclasses by putting it into the superClass?
Thanks in advance.
The
superClassconstructor is called first.The
superClassconstructor should be responsible for initializing thesuperClass'sdata membersand
firstSubClassshould initialize its own data members and call thesuperClass'sconstructor;More info on the constructor’s calling order here and you might also want to read about constructor initializer lists here
So, I would define
superClass,firstSubClassandsecondSubClassas :