-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStaticPolymorphism.cpp
More file actions
90 lines (74 loc) · 2.6 KB
/
Copy pathStaticPolymorphism.cpp
File metadata and controls
90 lines (74 loc) · 2.6 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <iostream>
#include <string>
using namespace std;
/*
Static Polymorphism (Compile-time polymorphism) in real life says that
the same action can behave differently depending on the input parameters.
For example, a Manual car can accelerate by a fixed amount or by a
specific amount you request. In programming, we achieve this via method
overloading: multiple methods with the same name but different signatures.
*/
//Program 2 demonstrates only compile-time polymorphism because it uses method overloading without inheritance or virtual functions. The compiler decides which overloaded accelerate() method to call based on the function arguments during compilation.
class ManualCar {
private:
string brand;
string model;
bool isEngineOn;
int currentSpeed;
int currentGear;
public:
ManualCar(string brand, string model) {
this->brand = brand;
this->model = model;
this->isEngineOn = false;
this->currentSpeed = 0;
this->currentGear = 0;
}
void startEngine() {
isEngineOn = true;
cout << brand << " " << model << " : Engine started." << endl;
}
void stopEngine() {
isEngineOn = false;
currentSpeed = 0;
cout << brand << " " << model << " : Engine turned off." << endl;
}
// Overloading accelerate - Static Polymorphism
void accelerate() {
if (!isEngineOn) {
cout << brand << " " << model << " : Cannot accelerate! Engine is off." << endl;
return;
}
currentSpeed += 20;
cout << brand << " " << model << " : Accelerating to " << currentSpeed << " km/h" << endl;
}
void accelerate(int speed) {
if (!isEngineOn) {
cout << brand << " " << model << " : Cannot accelerate! Engine is off." << endl;
return;
}
currentSpeed += speed;
cout << brand << " " << model << " : Accelerating to " << currentSpeed << " km/h" << endl;
}
void brake() {
currentSpeed -= 20;
if (currentSpeed < 0) currentSpeed = 0;
cout << brand << " " << model << " : Braking! Speed is now " << currentSpeed << " km/h" << endl;
}
void shiftGear(int gear) {
currentGear = gear;
cout << brand << " " << model << " : Shifted to gear " << currentGear << endl;
}
};
// Main function
int main() {
ManualCar* myManualCar = new ManualCar("Suzuki", "WagonR");
myManualCar->startEngine();
myManualCar->accelerate();
myManualCar->accelerate(40);
myManualCar->brake();
myManualCar->stopEngine();
// Cleanup
delete myManualCar;
return 0;
}