Sure! Here's a C++ program that demonstrates inheritance, polymorphism, and virtual functions in a clean, understandable way.
Scenario:
Let's model a simple shape hierarchy where different shapes like Circle and Rectangle are derived from a base class Shape.
✅ Concepts Covered:
-
Inheritance:
Circle
andRectangle
inherit fromShape
. -
Polymorphism: Using a base class pointer to call the derived class functions.
-
Virtual Function:
area()
anddisplay()
are virtual functions in the base class to enable runtime polymorphism.
✅ C++ Code:
#include <iostream>
#include <cmath> // for M_PI
using namespace std;
// Base class
class Shape {
public:
// Virtual functions to allow polymorphism
virtual double area() const {
return 0.0;
}
virtual void display() const {
cout << "This is a generic shape." << endl;
}
// Virtual destructor to ensure proper cleanup
virtual ~Shape() {}
};
// Derived class: Circle
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double area() const override {
return M_PI * radius * radius;
}
void display() const override {
cout << "Circle with radius: " << radius
<< " and area: " << area() << endl;
}
};
// Derived class: Rectangle
class Rectangle : public Shape {
private:
double length, width;
public:
Rectangle(double l, double w) : length(l), width(w) {}
double area() const override {
return length * width;
}
void display() const override {
cout << "Rectangle with length: " << length
<< ", width: " << width
<< " and area: " << area() << endl;
}
};
int main() {
// Array of base class pointers
Shape* shapes[3];
shapes[0] = new Shape(); // base class object
shapes[1] = new Circle(5.0); // derived class: Circle
shapes[2] = new Rectangle(4.0, 6.0); // derived class: Rectangle
cout << "--- Displaying Shape Info ---\n";
for (int i = 0; i < 3; ++i) {
shapes[i]->display(); // Polymorphic call
}
// Cleanup
for (int i = 0; i < 3; ++i) {
delete shapes[i]; // Virtual destructor ensures correct cleanup
}
return 0;
}
🔍 Output:
--- Displaying Shape Info ---
This is a generic shape.
Circle with radius: 5 and area: 78.5398
Rectangle with length: 4, width: 6 and area: 24
📌 Notes:
-
virtual
keyword enables runtime polymorphism. -
Override specifier (
override
) is used for clarity and error checking. -
Virtual destructors are essential when deleting derived objects through base class pointers.
Let me know if you'd like this extended with more features like abstract classes or interfaces.