-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPolymorphism.cpp
81 lines (64 loc) · 1.85 KB
/
Polymorphism.cpp
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// ----- POLYMORPHISM --------
// Existing in multiple forms
// Example: A father can exist in multiple forms as a father, brother, son, husband
// TWO TYPES: Compile Time Polymorphism, Run Time Polymorphism
//---------------------------------------------
// Compile Time Polymorphism
// Two types -> Function Overloading, Operator Overloading
// Function Overloading -> Parameter change can achieve function overloading
// -> Functions can be created with the same name but with different parameters
// Operator Overloading ->
// Example: '+' can be used to add numbers, concatenate strings, or as a function for subtraction
//----------------------------------------------
// Run Time Polymorphism -> Dynamic Polymorphism
// Function / Method Overriding
// Rules -> Method of parent and child class must be the same and must have the same parameters
// and this can be achieved through inheritance only
#include <iostream>
using namespace std;
class A {
public:
int a;
int b;
// Function Overloading
void sayHello() {
cout << "Hello.." << endl;
}
void sayHello(string name) {
cout << "Hello.. " << name << endl;
}
// Operator Overloading
void operator+ (A &obj) {
int val1 = this->a;
int val2 = obj.a;
cout << "Output: " << val2 - val1 << endl;
}
};
// Run Time Polymorphism - Method Overriding
class Human {
public:
void voice() {
cout << "Speaking.." << endl;
}
};
class Dog : public Human {
public:
void voice() {
cout << "Barking.." << endl;
}
};
int main() {
// Function Overloading
A obj;
obj.sayHello();
obj.sayHello("Aniket");
// Operator Overloading
A obj1, obj2;
obj1.a = 4;
obj2.a = 7;
obj1 + obj2;
// Run Time Polymorphism - Method Overriding
Dog labrador;
labrador.voice();
return 0;
}