Search⌘ K
AI Features

Solution: Polymorphic Notifications

Explore how to implement polymorphic notifications in C++ by declaring virtual functions and using inheritance. Understand how the override keyword ensures method correctness and how runtime polymorphism enables calling derived class methods through base class references.

We'll cover the following...
C++ 23
#include <iostream>
// Base Class
class Notification {
public:
// Virtual function allows derived classes to replace this behavior
virtual void send() {
std::cout << "Sending generic notification...\n";
}
};
// Derived Class 1
class Email : public Notification { // Inherits from Notification
public:
// Override keyword ensures we are correctly replacing the base method
void send() override {
std::cout << "Sending Email...\n";
}
};
// Derived Class 2
class SMS : public Notification {
public:
void send() override {
std::cout << "Sending SMS...\n";
}
};
void alertUser(Notification& note) {
// Calls the specific version of send() based on the actual object type
note.send();
}
int main() {
Email myEmail;
SMS mySMS;
alertUser(myEmail);
alertUser(mySMS);
return 0;
}
...