Implements pure virtual function in Interface
class IFTemperature {
public:
virtual ~IFTemperature() = default;
virtual double getTemperature() const = 0;
virtual void setTemperature(double temp) = 0;
virtual void display() const = 0;
};
Inherit the virtual class
#include <iostream>
#include <stdexcept>
class Celsius : public IFTemperature {
private:
double temperature;
static constexpr double MIN_TEMP = -273.15;
static constexpr double MAX_TEMP = 1.4e32;
public:
Celsius(double temp = 0.0) {
setTemperature(temp);
}
double getTemperature() const override {
return temperature;
}
void setTemperature(double temp) override {
if (temp < MIN_TEMP || temp > MAX_TEMP) {
throw std::out_of_range("Temperature out of range for Celsius.");
}
temperature = temp;
}
void display() const override {
std::cout << "Temperature: " << temperature << " °C" << std::endl;
}
};
class Fahrenheit : public IFTemperature {
private:
double temperature;
static constexpr double MIN_TEMP = -459.67;
static constexpr double MAX_TEMP = 2.5e32;
public:
Fahrenheit(double temp = 32.0) {
setTemperature(temp);
}
double getTemperature() const override {
return temperature;
}
void setTemperature(double temp) override {
if (temp < MIN_TEMP || temp > MAX_TEMP) {
throw std::out_of_range("Temperature out of range for Fahrenheit.");
}
temperature = temp;
}
void display() const override {
std::cout << "Temperature: " << temperature << " °F" << std::endl;
}
};
Usage
#include <memory> // shared_ptr
int main() {
try {
std::shared_ptr<IFTemperature> tempC = std::make_shared<Celsius>(25.0);
std::shared_ptr<IFTemperature> tempF = std::make_shared<Fahrenheit>(77.0);
tempC->display(); // "Temperature: 25 °C"
tempF->display(); // "Temperature: 77 °F"
tempC->setTemperature(30.0);
tempF->setTemperature(86.0);
tempC->display(); // "Temperature: 30 °C"
tempF->display(); // "Temperature: 86 °F"
// throw exception
tempC->setTemperature(-300.0);
}
catch (const std::out_of_range& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}