Why We Make a Function Pure Virtual in C
Why We Make a Function Pure Virtual in C
In C , a pure virtual function is a function declared in a base class that has no implementation and is intended to be overridden in derived classes. It is specified by assigning 0 in its declaration. This article explores the benefits and uses of pure virtual functions, which are a powerful tool for interface design and promoting code reuse through polymorphism.
1. Defining Interfaces
Pure virtual functions allow you to define an interface in a base class. Any derived class must provide an implementation for these functions, ensuring a consistent interface across different implementations.
2. Enforcing Implementation
By declaring a function as pure virtual, you enforce that any derived class must implement that function. This helps to prevent the creation of incomplete or abstract classes that cannot be instantiated.
3. Polymorphism
Pure virtual functions enable polymorphism, allowing you to write code that works with base class pointers or references while calling derived class implementations. This is essential for designing flexible and reusable code.
4. Abstract Classes
A class that contains at least one pure virtual function is considered an abstract class. Abstract classes cannot be instantiated directly, which is useful for defining a common base for a group of related classes.
Example
Here's a simple example to illustrate the concept:
#include iostream // Abstract base class class Shape { public: // Pure virtual function virtual void draw() 0; // No implementation }; // Derived class class Circle : public Shape { public: void draw() override { // Must implement draw std::cout "Drawing a circle." std::endl; } }; // Derived class class Square : public Shape { public: void draw() override { // Must implement draw std::cout "Drawing a square." std::endl; } }; int main() { Shape* shape1 new Circle(); Shape* shape2 new Square(); shape1-draw(); // Output: Drawing a circle. shape2-draw(); // Output: Drawing a square. delete shape1; delete shape2; return 0; }
Conclusion
Using pure virtual functions is a powerful way to establish a contract for derived classes, promote code reuse through polymorphism, and ensure that all derived classes provide specific functionality. This design pattern is widely used in object-oriented programming to create flexible and maintainable code.