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. Shape
is an abstract base class with a pure virtual functiondraw
. It cannot be instantiated on its own because it lacks an implementation fordraw
.2. Circle
andSquare
are derived classes ofShape
. They provide their own implementations of thedraw
function.- 3. In the
main
function, you cannot create an object of the abstract classShape
because it has a pure virtual function. However, you can create objects of the derived classes,Circle
andSquare
. 4. The key concept is the use of polymorphism. We can use base class pointers to point to objects of derived classes (
shape1
andshape2
). When calling thedraw
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.