-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPolymorphism.cpp
More file actions
65 lines (54 loc) · 1.55 KB
/
Polymorphism.cpp
File metadata and controls
65 lines (54 loc) · 1.55 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
63
64
65
#include <iostream>
using namespace std;
// Base class: Shape
class Shape {
public:
// Virtual function for runtime polymorphism (method overriding)
virtual void draw() {
cout << "🖼️ Drawing a shape!" << endl;
}
};
// Derived class: Circle, overrides the draw method of the Shape class
class Circle : public Shape {
public:
void draw() override {
cout << "⭕ Drawing a Circle!" << endl;
}
};
// Derived class: Square, overrides the draw method of the Shape class
class Square : public Shape {
public:
void draw() override {
cout << "🟦 Drawing a Square!" << endl;
}
};
// Method Overloading (Compile-time Polymorphism)
class Printer {
public:
// Overloaded methods with different parameter types
void print(int n) {
cout << "Printing an integer: " << n << endl;
}
void print(double n) {
cout << "Printing a double: " << n << endl;
}
void print(string s) {
cout << "Printing a string: " << s << endl;
}
};
int main() {
// Runtime Polymorphism: Using pointers to base class (Shape)
Shape* shape;
Circle circle;
Square square;
shape = &circle;
shape->draw(); // Output: ⭕ Drawing a Circle!
shape = □
shape->draw(); // Output: 🟦 Drawing a Square!
// Compile-time Polymorphism: Method Overloading
Printer printer;
printer.print(5); // Output: Printing an integer: 5
printer.print(5.5); // Output: Printing a double: 5.5
printer.print("Hello"); // Output: Printing a string: Hello
return 0;
}