Followers

Thursday, November 9, 2023

Pure virtual function in C++


A pure virtual function in C++ is a special type of virtual function that is declared in a base class but has no implementation there. Instead, it must be overridden in any derived class, making it mandatory for derived classes to provide their own implementation of the function. Pure virtual functions are also known as abstract functions, and they are declared using the "= 0" syntax.

Here's an example to illustrate pure virtual functions in C++:

cpp
#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 Square : public Shape { public: void draw() override { cout << "Drawing a square" << endl; } }; int main() { // Shape shape; // You cannot create an object of an abstract class Circle circle; Square square; // Polymorphic behavior through base class pointers Shape* shape1 = &circle; Shape* shape2 = &square; shape1->draw(); // Calls Circle's draw shape2->draw(); // Calls Square's draw return 0; }

In this example:

  1. 1. Shape is an abstract base class with a pure virtual function draw. It cannot be instantiated on its own because it lacks an implementation for draw.

  2. 2. Circle and Square are derived classes of Shape. They provide their own implementations of the draw function.

  3. 3. In the main function, you cannot create an object of the abstract class Shape because it has a pure virtual function. However, you can create objects of the derived classes, Circle and Square.

  4. 4. The key concept is the use of polymorphism. We can use base class pointers to point to objects of derived classes (shape1 and shape2). When calling the draw function through these pointers, the appropriate implementation in the derived class is invoked, demonstrating polymorphic behavior.

Pure virtual functions are commonly used in C++ to define interfaces, ensuring that derived classes provide specific functionality while allowing polymorphism to work effectively.

No comments:

Post a Comment