OOP: POLYMORPHISM
Pure Virtual Functions
A pure virtual function is a virtual function that has no required implementation in the base class and must be implemented by concrete derived classes.
Syntax:
virtual return_type function_name(parameters) = 0;
Example:
virtual double area() const = 0;
What It Means
A pure virtual function says:
Every concrete child class must provide this behavior.
It creates a common interface.
Complete Example
#include <iostream>
using namespace std;
class Shape {
public:
virtual ~Shape() = default;
virtual double area() const = 0;
};
class Rectangle : public Shape {
private:
double width;
double height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
double area() const override {
return width * height;
}
};
class Square : public Shape {
private:
double side;
public:
Square(double s) : side(s) {}
double area() const override {
return side * side;
}
};
int main() {
Rectangle rectangle(4, 5);
Square square(3);
Shape* shape = &rectangle;
cout << shape->area() << endl;
shape = □
cout << shape->area() << endl;
return 0;
}
Output:
20
9
Important Rule
If a class has at least one pure virtual function, it becomes an abstract class.
This is not allowed:
// Shape shape; // error: Shape is abstract
But this is allowed:
Shape* shape;
Shape& reference = rectangle;
You can use pointers and references to abstract classes.
Viva Answer
A pure virtual function is declared with = 0 and forces derived classes to implement it. A class with at least one pure virtual function becomes abstract and cannot be instantiated directly.
Quick Check
- What does
= 0mean in a virtual function declaration? - Can we create an object of a class with a pure virtual function?
- What happens if a derived class does not implement all pure virtual functions?