I am very new to C++ so apologies for the wrong and probably confusion terminology in the title. Would love to know what this is properly called.
I am trying to add an object with an overloaded constructor to another object. However, it always takes the default constructor instead of my overloaded one.
Consider the following scenario. I have a water pump with an optional water level sensor. I have a separate class for my water level sensor.
class WaterLevelSensor{
private:
bool _waterLevelOK;
bool _reversedLogic;
public:
WaterLevelSensor();
WaterLevelSensor(bool reversedLogic);
};
WaterLevelSensor::WaterLevelSensor(){
_reversedLogic = true;
}
WaterLevelSensor::WaterLevelSensor(bool reversedLogic){
_reversedLogic = reversedLogic;
}
and a pump class
class Pump{
private:
bool _hasWaterSensor = false;
WaterLevelSensor waterSensor;
public:
Pump();
void addWaterSensor(reversedLogic);
};
Pump::Pump(){}
void Pump::addWaterSensor(reversedLogic){
WaterLevelSensor waterSensor(reversedLogic);
_hasWaterSensor = true;
}
If I do the following, the water sensor will still have reversedLogic == true, even though I passed false. I assume this is due to the fact that during the creation of the pump the default constructor of the sensor is already called, passing the reversedLogic = true. How would I solve this? I do realise I could fix it by creating a function like setLogic() that allows to alter the variable. But I am just curious what the proper solution to this would be without creating this.
int main(){
Pump pump;
pump.addWaterSensor(false);
return 0;
}
WaterLevelSensor(bool reversedLogic = true);should be enoughvoid addWaterSensor(reversedLogic)be:void Pump::addWaterSensor(bool reversedLogic)?