-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathabstract_base_class.cpp
More file actions
62 lines (49 loc) · 1.4 KB
/
Copy pathabstract_base_class.cpp
File metadata and controls
62 lines (49 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <string>
using namespace std;
// Abstract base class
class Shape {
public:
// Pure virtual function (must be overridden in derived classes)
virtual double area() = 0; // Declared but not defined, = 0 indicates it's pure
virtual string getType() = 0;
virtual ~Shape() {} // Virtual destructor
};
// Derived class 1
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double area() override {
return 3.14159 * radius * radius;
}
string getType() override {
return "Circle";
}
};
// Derived class 2
class Rectangle : public Shape {
private:
double width;
double height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
double area() override {
return width * height;
}
string getType() override {
return "Rectangle";
}
};
int main() {
// Create pointers to Shape (abstract class)
Shape* shape1 = new Circle(5.0);
Shape* shape2 = new Rectangle(4.0, 6.0);
// Polymorphism: Calling area() through the base class pointer, but the correct derived class method is executed
cout << "Area of " << shape1->getType() << ": " << shape1->area() << endl; // Calls Circle::area()
cout << "Area of " << shape2->getType() << ": " << shape2->area() << endl; // Calls Rectangle::area()
delete shape1;
delete shape2;
return 0;
}