OOP: POLYMORPHISM
Abstract Classes
An abstract class is a class that cannot be instantiated directly.
A class becomes abstract when it has at least one pure virtual function.
Purpose
Abstract classes are used to define a common interface for derived classes.
They can contain:
- Pure virtual functions.
- Normal virtual functions.
- Normal member functions.
- Data members.
- Constructors.
- Destructors.
Complete Example
#include <iostream>
#include <string>
using namespace std;
class Payment {
protected:
double amount;
public:
Payment(double paymentAmount) : amount(paymentAmount) {}
virtual ~Payment() = default;
virtual void process() const = 0;
void showAmount() const {
cout << "Amount: " << amount << endl;
}
};
class CardPayment : public Payment {
public:
CardPayment(double amount) : Payment(amount) {}
void process() const override {
cout << "Processing card payment" << endl;
}
};
int main() {
CardPayment payment(1500);
payment.showAmount();
payment.process();
return 0;
}
Output:
Amount: 1500
Processing card payment
Abstract Class vs Interface
C++ does not have a separate interface keyword like Java.
A C++ class can behave like an interface if it mainly contains pure virtual functions.
class Printable {
public:
virtual ~Printable() = default;
virtual void print() const = 0;
};
Common Mistake
This is illegal:
// Payment payment(1000); // error: Payment is abstract
This is legal:
Payment* paymentPtr;
Pointers and references to abstract classes are allowed.
Viva Answer
An abstract class is a class that has at least one pure virtual function and cannot be instantiated directly. It is used as a base class to define a common interface for derived classes.
Quick Check
- What makes a class abstract?
- Can an abstract class have normal member functions?
- Can we create a pointer to an abstract class?