polymorphism
polymorphism
cpp 1
1 #include <iostream>
2 #include <cmath> // For M_PI
3 using namespace std;
4
5 // Base class
6 class Shape {
7 protected:
8 double Area; // Attribute to store the area
9
10 public:
11 // Constructor that initializes Area to zero
12 Shape() : Area(0) {}
13
14 // Pure virtual function
15 virtual void Calculate_Area() = 0;
16
17 // Method to display the area
18 virtual void Display() {
19 cout << "Area: " << Area << endl;
20 }
21
22 };
23
24 // Derived class for Circle
25 class Circle : public Shape {
26 private:
27 double radius; // Attribute for radius
28
29 public:
30 // Constructor that takes radius as an argument
31 Circle(double r) : radius(r)
32 {
33
34 }
35
36 // Override Calculate_Area method
37 void Calculate_Area() override
38 {
39 Area = 3.14 * radius * radius; // Area of Circle = π * radius^2
40 }
41
42 // Override Display method
43 void Display() override
44 {
45 cout << "Circle with radius " << radius << " has ";
46 Shape::Display(); // Call the base class Display
47 }
48 };
49
C:\Users\Iqra\source\repos\Project22\Project22\Source.cpp 2
50 // Derived class for Rectangle
51 class Rectangle : public Shape {
52 private:
53 double length; // Attribute for length
54 double breadth; // Attribute for breadth
55
56 public:
57 // Constructor that takes length and breadth as arguments
58 Rectangle(double l, double b) : length(l), breadth(b) {}
59
60 // Override Calculate_Area method
61 void Calculate_Area() override {
62 Area = length * breadth; // Area of Rectangle = Length * Breadth
63 }
64
65 // Override Display method
66 void Display() override {
67 cout << "Rectangle with length " << length << " and breadth " <<
breadth << " has ";
68 Shape::Display(); // Call the base class Display
69 }
70 };
71
72 // Driver program
73 int main() {
74 Shape* p; // Pointer of type Shape
75 Circle C1(5); // Create a Circle object with radius 5
76 Rectangle R1(4, 6); // Create a Rectangle object with length 4 and
breadth 6
77
78 // Calculate and display area for Circle
79 p = &C1; // Point to Circle object
80 p->Calculate_Area(); // Calculate area of Circle
81 p->Display(); // Display area of Circle
82
83 // Calculate and display area for Rectangle
84 p = &R1; // Point to Rectangle object
85 p->Calculate_Area(); // Calculate area of Rectangle
86 p->Display(); // Display area of Rectangle
87
88 return 0; // End of program
89 }