Suppose several kinds of notices have a label. A function receiving a reference to the general notice type should still get the label for the actual object. A virtual function supports that runtime choice. Unlike a function template, which forms functions for concrete types during compilation, this shared base interface lets a call select derived behavior while the program runs.
#include <iostream>
#include <string>
class Notice {
public:
virtual std::string label() const { return "Notice"; }
virtual ~Notice() = default;
};
class Reminder : public Notice {
public:
std::string label() const override { return "Reminder"; }
};
int main() {
Reminder item;
const Notice& view = item;
std::cout << view.label() << '\n';
}
The base declares label with virtual. The derived class supplies an override with the same parameter list and compatible return type; its const qualification also matches. override asks the compiler to check that this really replaces a virtual operation. A spelling or signature mismatch becomes a helpful diagnostic rather than an unrelated function.
view refers to the existing derived object; it does not copy it. Calling view.label() therefore selects Reminder::label. This choice is called dynamic dispatch. The declared type Notice tells you which operations the reference allows; the actual Reminder object determines which override runs. The reference does not turn the reminder into a plain notice.
The virtual destructor shown here is a safe default for this polymorphic base. The = default spelling asks the compiler to provide its normal destructor implementation; it is not a return value. A later lesson examines destruction through base ownership; there is no manual deletion in this task.
The editor already supplies a virtual base operation and two derived classes. Complete each override's returned text. The probes deliberately call through const Delivery&, not directly through derived names, so you can observe the shared interface selecting two different behaviors. Keep override and const intact while changing the method bodies.
In this call-flow example, the expression uses an Animal reference, but the actual object is a Dog. Because sound is virtual, the call selects the Dog override.
Edit main.cpp; the supplied Console probes already call your code.
Pickup::label return "Collect at desk". Expect First: Collect at desk.Courier::label return "Deliver to door". Expect Second: Deliver to door.Use Run to inspect the Console, then Submit to check your work.