Abstraction using Abstract Classes
An abstract class is a class that cannot be used to create objects directly.
It is usually used as a base class that defines a common interface for derived classes.
Pure Virtual Function
A pure virtual function is declared with = 0.
virtual void process() = 0;
If a class has at least one pure virtual function, it becomes abstract.
Why Abstract Classes Create Abstraction
An abstract class tells outside code:
You can use this common interface.
You do not need to know the exact derived class implementation.
Example:
payment->process(500);
The caller does not need to know whether it is card payment, mobile payment, or cash payment.
Complete Example
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
class PaymentProcessor {
public:
virtual ~PaymentProcessor() = default;
virtual void process(double amount) const = 0;
};
class CardPayment : public PaymentProcessor {
public:
void process(double amount) const override {
cout << "Processing card payment: " << amount << endl;
}
};
class MobilePayment : public PaymentProcessor {
public:
void process(double amount) const override {
cout << "Processing mobile payment: " << amount << endl;
}
};
int main() {
vector<unique_ptr<PaymentProcessor>> payments;
payments.push_back(make_unique<CardPayment>());
payments.push_back(make_unique<MobilePayment>());
for (const auto& payment : payments) {
payment->process(750);
}
return 0;
}
Output:
Processing card payment: 750
Processing mobile payment: 750
What To Notice
PaymentProcessor is abstract because it has a pure virtual function.
This is not allowed:
// PaymentProcessor processor; // error
But this is allowed:
PaymentProcessor* processor;
Pointers and references to abstract classes are allowed because they can refer to concrete derived objects.
Abstract Class vs Concrete Class
| Type | Meaning |
|---|---|
| Abstract class | Has at least one pure virtual function; cannot be instantiated directly. |
| Concrete class | Implements all pure virtual functions; objects can be created. |
Viva Answer
Abstract classes support abstraction by defining a common interface and hiding the derived implementation details. A class becomes abstract when it has at least one pure virtual function. We cannot create an object of an abstract class, but we can use pointers or references to it.
Quick Check
- What makes a class abstract?
- Why can
PaymentProcessor*exist even thoughPaymentProcessorobjects cannot? - What must a derived class do to become concrete?