The short answer
An abstract class sets the rules for a group of related classes. You can’t create objects from it by itself. Each derived class must provide the functions the abstract class declares as pure virtual, and each one supplies its own version of them.
Three things it does
- It defines an interface. It declares the operations every derived class has, such as
write()in the example below. - It blocks direct object creation. A declaration like
Logger logger;won’t compile whenLoggeris abstract. - It can share code. Ordinary functions in the base class are inherited, so derived classes don’t need to repeat them.
An example with loggers
A program may need to log messages in more than one way. The base class says what a logger does, and each derived class decides where the message goes.
#include <iostream>
#include <string>
class Logger {
public:
virtual ~Logger() = default;
virtual void write(const std::string& message) = 0; // Every logger must provide this
void log_error(const std::string& message) { // Shared by all loggers
write("ERROR: " + message);
}
};
class ConsoleLogger : public Logger {
public:
void write(const std::string& message) override {
std::cout << message << "\n";
}
};
class SilentLogger : public Logger {
public:
void write(const std::string&) override {
// Discards the message
}
};
void report(Logger& logger) {
logger.log_error("disk is almost full");
}
int main() {
ConsoleLogger console;
SilentLogger silent;
report(console); // Prints: ERROR: disk is almost full
report(silent); // Prints nothing
}
Logger has one pure virtual function, write(), so it is abstract. log_error() is an ordinary function in the base class. It adds a prefix and calls write() without knowing which logger it’s dealing with. ConsoleLogger and SilentLogger both inherit log_error(), but each one writes the message in its own way.
Why the rules help
If you write a new logger class and leave out write(), the compiler reports an error when you try to create an object of that class. The rules catch missing functions before the program runs.
Where polymorphism comes in
report() takes a Logger&, so the same call works with any logger. This is a simple case of polymorphism in c: the same call does different things depending on which object it receives.
What it does not do
- It doesn’t check that each function behaves sensibly. The compiler checks that the function exists, not that it is correct.
- It doesn’t write the derived classes for you. You still have to implement them.
When you would want one
Use an abstract class when several classes should share one set of operations, but each one needs its own details. If the base class would make no sense as a standalone object, it may be a good candidate.