Repository navigation
Expand file tree
/
Copy pathencapsulation.cpp
More file actions
86 lines (73 loc) · 2.58 KB
/
Copy pathencapsulation.cpp
File metadata and controls
86 lines (73 loc) · 2.58 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
// Encapsulation: keep data private and expose a small, safe public interface.
// Setters validate their input, so an object can never reach an invalid state.
#include <iostream>
#include <stdexcept>
#include <string>
class Employee {
private:
std::string name;
int age = 18;
double salary = 0;
public:
Employee(const std::string& name, int age, double salary) {
setName(name); // reuse the validation instead of duplicating it
setAge(age);
setSalary(salary);
}
// Getters are const: reading never changes the object
const std::string& getName() const { return name; }
int getAge() const { return age; }
double getSalary() const { return salary; }
// Setters return *this so calls can be chained
Employee& setName(const std::string& newName) {
if (newName.empty()) throw std::invalid_argument("name cannot be empty");
name = newName;
return *this;
}
Employee& setAge(int newAge) {
if (newAge < 18 || newAge > 65) throw std::invalid_argument("age must be between 18 and 65");
this->age = newAge; // 'this' points to the object the function was called on
return *this;
}
Employee& setSalary(double newSalary) {
if (newSalary < 0) throw std::invalid_argument("salary cannot be negative");
salary = newSalary;
return *this;
}
// Behaviour that enforces a business rule
void giveRaise(double percent) {
if (percent <= 0 || percent > 20) {
std::cout << " Raise of " << percent << "% rejected: must be between 0 and 20%\n";
return;
}
salary += salary * percent / 100;
std::cout << " " << name << " got a " << percent << "% raise\n";
}
void print() const { std::cout << " " << name << ", " << age << " years, salary " << salary << '\n'; }
};
int main() {
Employee e("Areeba Noor", 26, 120000);
e.print();
std::cout << "\nChained setters:\n";
e.setName("Areeba N. Khan").setAge(27);
e.print();
std::cout << "\nBusiness rules:\n";
e.giveRaise(10);
e.giveRaise(45);
e.print();
std::cout << "\nInvalid data is refused:\n";
try {
e.setAge(12);
} catch (const std::invalid_argument& ex) {
std::cout << " Error: " << ex.what() << '\n';
}
try {
Employee bad("", 30, 1000);
} catch (const std::invalid_argument& ex) {
std::cout << " Error: " << ex.what() << '\n';
}
// e.salary = -5; // compile error: 'salary' is private
std::cout << "\nThe object is still valid:\n";
e.print();
return 0;
}