What is Pure Virtual function ? Why do we need pure virtual function ?
In : BCA Subject : OOPS and Data StructuresA pure virtual function is a special kind of function in C++ that:
Has no implementation in the base class
Forces derived classes to provide their own implementation.
We use pure virtual functions for:
1. Creating Abstract Classes (Interfaces)
An abstract class is a class that cannot be used to create objects directly . It exists only to be inherited by other classes.
2. Enforcing a Common Interface
When multiple classes inherit from a base class with pure virtual functions, they all have to implement those functions — ensuring a common structure .
Example :
#include <iostream>
using namespace std;
// Base class with pure virtual function
class Shape {
public:
// Pure virtual function
virtual float area() = 0; // No body here
};
// Derived class - Circle
class Circle : public Shape {
private:
float radius;
public:
Circle(float r) {
radius = r;
}
// Must override area()
float area() override {
return 3.14f * radius * radius;
}
};
// Another derived class - Square
class Square : public Shape {
private:
float side;
public:
Square(float s) {
side = s;
}
// Must override area()
float area() override {
return side * side;
}
};
int main() {
// Shape s; Error: Cannot create object of abstract class
Circle c(5);
Square s(4);
cout << "Circle Area: " << c.area() << endl; // Works
cout << "Square Area: " << s.area() << endl; // Works
return 0;
}