-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpolymorphism.cpp
More file actions
59 lines (48 loc) · 1.35 KB
/
polymorphism.cpp
File metadata and controls
59 lines (48 loc) · 1.35 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
#include <iostream>
using namespace std;
// --------- Compile-time polymorphism (Function Overloading) ----------
class Calculator {
public:
// Add two integers
int add(int a, int b) {
return a + b;
}
// Add three integers (same function name, different parameters)
int add(int a, int b, int c) {
return a + b + c;
}
};
// --------- Run-time polymorphism (Virtual functions) ----------
class Animal {
public:
virtual void sound() { // Virtual function
cout << "Animal makes a sound" << endl;
}
};
class Dog : public Animal {
public:
void sound() override { // Override base class function
cout << "Dog barks" << endl;
}
};
class Cat : public Animal {
public:
void sound() override {
cout << "Cat meows" << endl;
}
};
int main() {
// Compile-time polymorphism: function overloading
Calculator calc;
cout << "Add 2 numbers: " << calc.add(5, 7) << endl;
cout << "Add 3 numbers: " << calc.add(1, 2, 3) << endl;
// Run-time polymorphism: virtual function example
Animal* animalPtr;
Dog d;
Cat c;
animalPtr = &d; // Point to Dog object
animalPtr->sound(); // Calls Dog's sound()
animalPtr = &c; // Point to Cat object
animalPtr->sound(); // Calls Cat's sound()
return 0;
}