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 = □
shape1->draw(); // Calls Circle's draw
shape2->draw(); // Calls Square's draw
return 0;
}In this example:
1. Shapeis an abstract base class with a pure virtual functiondraw. It cannot be instantiated on its own because it lacks an implementation fordraw.2. CircleandSquareare derived classes ofShape. They provide their own implementations of thedrawfunction.- 3. In the
mainfunction, you cannot create an object of the abstract classShapebecause it has a pure virtual function. However, you can create objects of the derived classes,CircleandSquare. 4. The key concept is the use of polymorphism. We can use base class pointers to point to objects of derived classes (
shape1andshape2). When calling thedrawfunction 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.


