'C++ init a class member inside a subclass constructor init list
Is there a way to init the member of a class inside the initialisation list of one of its subclasses ? let me explain, since it is way easier to visualise like that:
Inside a class I have a bitfield struct
class bitFieldInterface{
struct dataBlock{
uint32_t engineDataRPM : s_engineDataRPM .size;
uint32_t engineDataInstantConsumption : s_InstantConsumption.size;
...
uint32_t vehicleGpsLocation : s_vehicleGEneralInfoGpsLocation.size;
uint32_t vehicleGpsSpeed : s_vehicleGeneralInfoGpsSpeed.size;
...
uint32_t vehicleInfoDimensionX : s_vehicleInfoDimensionX .size;
uint32_t vehicleInfoDimensionY : s_vehicleInfoDimensionY .size;
...
} m_dataBlock;
}
in total, there are over 40 distinct fields.
I could just init them all in the constructor init list:
bitFieldInterface() :
m_dataBlock.engineDataRPM{s_engineDataRPM.defaultValue},
m_dataBlock.engineDataInstantConsumption{s_engineDataInstantConsumption.defaultValue},
...
m_dataBlock.vehicleGpsLocation{s_vehicleGpsLocation.defaultValue},
m_dataBlock.vehicleGpsSpeed{s_vehicleGpsSpeed.defaultValue},
...
m_dataBlock.vehicleInfoDimensionX{s_vehicleInfoDimensionX.defaultValue},
m_dataBlock.vehicleInfoDimensionY{s_vehicleInfoDimensionY.defaultValue},
...
{}
but since there are different categories I wanted to add more structure to my code and divide them into subclasses like so:
class EngineData
class vehicleGps
class vehicleInfo
...
and inside each class constructor initialize the corresponding fields of the main class EngineData():
m_dataBlock.engineDataRPM{s_engineDataRPM.defaultValue},
m_dataBlock.engineDataInstantConsumption{s_engineDataInstantConsumption.defaultValue},
...
{}
vehicleGps():
m_dataBlock.vehicleGpsLocation{s_vehicleGpsLocation.defaultValue},
m_dataBlock.vehicleGpsSpeed{s_vehicleGpsSpeed.defaultValue},
...
{}
and in the main class I would just call each constructor: bitFieldInterface():
EngineData{},
vehicleGps{},
vehicleInfo{},
...
{}
is there a way to do this, while keeping the m_dataBlock inside the bitFieldInterface class ?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
