Abstract classes, interfaces and week 6 review
In the previous lesson the Shape class had an implementation of area() that returned 0, which is not very honest: a generic shape has no area. When a base class exists only to define a contract that derived classes must fulfill, it is declared abstract. A pure virtual function is written with = 0 at the end: virtual double area() const = 0;. A class with at least one pure virtual function is abstract: you cannot create objects of it, only of derived classes that implement all pure functions. This way the compiler forces you to fulfill the contract.
Interfaces in C++
C++ has no interface keyword, but the pattern is clear: a class with only pure virtual functions, no data, and a virtual destructor. The classes that implement it inherit from it publicly. Client code depends on the interface and not on concrete classes, so you can swap one implementation for another without touching the client. This is very useful for testing: you replace a real notifier with a fake one that only stores messages. An abstract class can also have data and regular functions; the pure interface is just the extreme case.
#include <iostream>
#include <string>
#include <vector>
class Notifier { // interface
public:
virtual ~Notifier() = default;
virtual void send(const std::string& message) = 0;
};
class ConsoleNotifier : public Notifier {
public:
void send(const std::string& message) override {
std::cout << "[console] " << message << '\n';
}
};
class MemoryNotifier : public Notifier { // useful in tests
public:
void send(const std::string& message) override { sent_.push_back(message); }
std::size_t count() const { return sent_.size(); }
private:
std::vector<std::string> sent_;
};
void alert(Notifier& notifier, const std::string& what) {
notifier.send("ALERT: " + what);
}
int main() {
ConsoleNotifier console;
MemoryNotifier memory;
alert(console, "disk almost full"); // [console] ALERT: disk almost full
alert(memory, "disk almost full");
alert(memory, "high temperature");
std::cout << memory.count() << " messages stored\n"; // 2 messages stored
// Notifier n; // error: cannot instantiate an abstract class
return 0;
}final and dynamic_cast
Two more tools to close the topic. The word final prevents further overriding of a function (void f() override final;) or further inheriting from a class (class Leaf final : public Node), useful when the design must not be extended. On the other hand, dynamic_cast lets you ask at run time whether a pointer to the base really points to a certain derived class: it returns a valid pointer or nullptr. Use it very rarely: if you often need to ask the type, it is a sign that a virtual function is missing from the interface. It requires the base to have at least one virtual function.
#include <iostream>
class Base {
public:
virtual ~Base() = default;
};
class Special final : public Base { // nobody can derive from Special
public:
void onlySpecial() const { std::cout << "special feature\n"; }
};
class Plain : public Base {};
void tryFeature(const Base& b) {
if (const Special* s = dynamic_cast<const Special*>(&b)) {
s->onlySpecial();
} else {
std::cout << "not special\n";
}
}
int main() {
Special s;
Plain p;
tryFeature(s); // special feature
tryFeature(p); // not special
return 0;
}Week review: public inheritance expresses "is a"; the base constructor runs first and its destructor last; hiding is not overriding; polymorphism needs virtual functions, override, a virtual destructor in the base and access through pointer or reference; copying by value produces slicing; pure virtual functions create abstract classes and interfaces. Typical mistakes: forgetting the virtual destructor, forgetting override and creating a new function by accident, and storing objects by value in a vector of the base class.
जो सीखा उसे परखें
प्रश्न 1 / 6How is a pure virtual function declared?
✎ मेरे नोट्स
केवल इस ब्राउज़र में सहेजा गया। खाते में रखने के लिए साइन इन करें।0/5000 अक्षर