Security System Friend Class
Create two classes SecuritySystem and ControlPanel.
The SecuritySystem class should have the private members: bool isArmed, and bool alarmTriggered
The ControlPanel class should contain a pointer to a SecuritySystem object and be declared as a friend of SecuritySystem. The ControlPanel class should have methods to:
armSystem(): Arms the security system.disarmSystem(): Disarms the security system.triggerAlarm(): Triggers the alarm if the system is armed.checkStatus(): Displays whether the system is armed and whether the alarm is triggered.
In main(), create a SecuritySystem object and then create a ControlPanel object that manages this SecuritySystem through a pointer. Use the ControlPanel object to manage the system's state by arming, disarming, triggering the alarm, and checking the status.
Hint
- The
ControlPanelclass should have access to the private members ofSecuritySystemthrough the friend class relationship. - The
ControlPanelshould have a constructor that takes a pointer to aSecuritySystemobject.
Answer
#include <iostream>
class SecuritySystem {
private:
bool isArmed;
bool alarmTriggered;
public:
SecuritySystem() : isArmed(false), alarmTriggered(false) {}
// Declare ControlPanel as a friend class
friend class ControlPanel;
};
class ControlPanel {
private:
SecuritySystem* system; // Pointer to a SecuritySystem object
public:
// Constructor that takes a pointer to a SecuritySystem object
ControlPanel(SecuritySystem* sys) : system(sys) {}
void armSystem() {
system->isArmed = true;
system->alarmTriggered = false;
std::cout << "Security system armed." << std::endl;
}
void disarmSystem() {
system->isArmed = false;
system->alarmTriggered = false;
std::cout << "Security system disarmed." << std::endl;
}
void triggerAlarm() {
if (system->isArmed) {
system->alarmTriggered = true;
std::cout << "Alarm triggered!" << std::endl;
} else {
std::cout << "System is not armed. Cannot trigger alarm." << std::endl;
}
}
void checkStatus() {
std::cout << "Security System Status:" << std::endl;
std::cout << "Armed: " << (system->isArmed ? "Yes" : "No") << std::endl;
std::cout << "Alarm Triggered: " << (system->alarmTriggered ? "Yes" : "No") << std::endl;
}
};
int main() {
SecuritySystem myHomeSecurity;
ControlPanel myControlPanel(&myHomeSecurity); // Pass pointer to ControlPanel
myControlPanel.checkStatus();
myControlPanel.armSystem();
myControlPanel.checkStatus();
myControlPanel.triggerAlarm();
myControlPanel.checkStatus();
myControlPanel.disarmSystem();
myControlPanel.checkStatus();
return 0;
}