Why do we need virtual functions in C++?

 

Virtual functions in C++ are used to achieve polymorphism, a key concept in object-oriented programming. Polymorphism allows you to write code that works with objects of different classes in a unified way, facilitating code reuse and flexibility. Virtual functions enable dynamic binding, allowing the appropriate function to be called based on the actual type of the object.

Here's an example to illustrate the need for virtual functions:

cpp
#include <iostream> class Shape { public: virtual void draw() { std::cout << "Drawing a shape." << std::endl; } }; class Circle : public Shape { public: void draw() override { std::cout << "Drawing a circle." << std::endl; } }; class Square : public Shape { public: void draw() override { std::cout << "Drawing a square." << std::endl; } }; int main() { Circle circle; Square square; Shape* shapePtr; shapePtr = &circle; shapePtr->draw(); // Calls Circle's draw() shapePtr = &square; shapePtr->draw(); // Calls Square's draw() return 0; }

In this example, we have a base class Shape with a virtual function draw(). We also have two derived classes, Circle and Square, each of which overrides the draw() function.

By declaring the draw() function as virtual in the base class, we enable polymorphism. This means that when we call the draw() function using a pointer to the base class (Shape*), the correct version of the function is determined at runtime based on the actual type of the object pointed to.

Without virtual functions, calling shapePtr->draw() would always call the draw() function of the base class, regardless of the actual object type. Virtual functions provide the ability to create code that adapts to the specific type of object being used, allowing you to write more flexible and reusable code.

In summary, virtual functions are essential for achieving polymorphism and dynamic binding in C++. They enable the ability to work with objects of different classes through a common interface, leading to more maintainable and extensible code.

Comments