What is a Pure Virtual Function?
A pure virtual function is a virtual function that has no body in the base class and must be overridden in any derived class.
It is used to create a blueprint (or interface) for other classes.
A class that contains at least one pure virtual function is called an abstract class.
π Syntax of Pure Virtual Function
class Base {
public:
virtual void show() = 0; // pure virtual function
};
The = 0
tells the compiler that this function is pure and has no definition in the base class.
π§ Real-Life Analogy
Think of an abstract concept like a “Shape”. You donβt know what a shape looks like until it’s made into a Circle, Rectangle, or Triangle.
So “Shape” just declares that all shapes must have an area()
function β but each derived class defines it differently.
π§ Characteristics of Pure Virtual Functions
- Declared using
= 0
syntax. - No implementation in base class.
- Forces derived class to override the function.
- Makes the base class abstract.
- Cannot create objects of abstract class.
βοΈ Example: Pure Virtual Function in Action
#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};
class Circle : public Shape {
public:
void draw() override {
cout << "Drawing a Circle." << endl;
}
};
class Rectangle : public Shape {
public:
void draw() override {
cout << "Drawing a Rectangle." << endl;
}
};
int main() {
Shape* s1 = new Circle();
Shape* s2 = new Rectangle();
s1->draw(); // Output: Drawing a Circle.
s2->draw(); // Output: Drawing a Rectangle.
delete s1;
delete s2;
return 0;
}
π What is an Abstract Class?
A class is called abstract if it contains at least one pure virtual function.
π Properties of Abstract Classes:
- Cannot create objects directly from an abstract class.
- Can have constructors and data members.
- Can be used as base classes.
- Used to define common interfaces.
β Benefits of Using Pure Virtual Functions
- Helps in designing flexible and reusable code.
- Supports runtime polymorphism.
- Provides common interfaces for all derived classes.
- Enforces a contract: derived classes must implement specific behavior.
π Summary Table
Feature | Description |
---|---|
Syntax | virtual void func() = 0; |
Belongs to | Abstract base class |
Object Creation | Not allowed for abstract class |
Must be overridden | Yes, in every derived class |
Used for | Creating interfaces or base class templates |
β Error Example (if not overridden)
class Base {
public:
virtual void show() = 0;
};
class Derived : public Base {
// No show() function defined here
};
int main() {
Derived d; // β Error: cannot instantiate abstract class
return 0;
}
π― Real-world Usage
- GUI frameworks (e.g., abstract “Button” class)
- Game engines (e.g., abstract “GameObject” or “Entity” class)
- File handling libraries, Shape classes, and more