Polymorphism is one of the fundamental principles of object-oriented programming (OOP). In C++, polymorphism allows objects of different classes to be treated as objects of a common base class. Polymorphism enables to write code that works with objects of various derived classes in a consistent manner.
Here's a sample C++ program demonstrating polymorphism with comments and Sample Output:
#include <iostream>
// Base class
class Shape {
public:
virtual double area() const = 0; // Pure virtual function
virtual void display() const {
std::cout << "This is a shape." << std::endl;
}
};
// Derived class 1: Circle
class Circle : public Shape {
public:
Circle(double radius) : radius(radius) {}
double area() const override {
return 3.14159 * radius * radius;
}
void display() const override {
std::cout << "This is a circle with radius " << radius << std::endl;
}
private:
double radius;
};
// Derived class 2: Rectangle
class Rectangle : public Shape {
public:
Rectangle(double length, double width) : length(length), width(width) {}
double area() const override {
return length * width;
}
void display() const override {
std::cout << "This is a rectangle with length " << length << " and width " << width << std::endl;
}
private:
double length;
double width;
};
int main() {
Shape* shapes[2]; // Array of base class pointers
Circle circle(5.0);
Rectangle rectangle(4.0, 6.0);
shapes[0] = &circle;
shapes[1] = &rectangle;
std::cout << "Shape Information:" << std::endl;
for (int i = 0; i < 2; i++) {
shapes[i]->display(); // Polymorphic call to display()
std::cout << "Area: " << shapes[i]->area() << std::endl;
std::cout << std::endl;
}
return 0;
}
Shape Information:
This is a circle with radius 5
Area: 78.5398
This is a rectangle with length 4 and width 6
Area: 24
question
question2