-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencapsulation.cpp
More file actions
145 lines (109 loc) · 2.63 KB
/
encapsulation.cpp
File metadata and controls
145 lines (109 loc) · 2.63 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
//This example demonstrates encapsulation, data protection, and object interaction
/*
#include <iostream>
using namespace std;
class BankAccount
{
private:
int balance;
string accountHolder;
int accountNumber;
static int totalAccounts; // Shared by all objects
public:
// Constructor
BankAccount(string name, int initialBalance)
{
accountHolder = name;
balance = initialBalance;
totalAccounts++;
accountNumber = totalAccounts;
cout << "Account created for " << name << " (A/C No: " << accountNumber << ")" << endl;
}
void deposit(int amount)
{
if(amount > 0)
{
balance += amount;
cout << "Deposited: Rs " << amount << endl;
}
else
{
cout << "Invalid amount!" << endl;
}
}
void withdraw(int amount)
{
if(amount <= 0)
{
cout << "Invalid amount!" << endl;
}
else if(amount <= balance)
{
balance -= amount;
cout << "Withdrawn: Rs " << amount << endl;
}
else
{
cout << "Insufficient balance!" << endl;
}
}
void showBalance()
{
cout << "Account Holder: " << accountHolder << endl;
cout << "Account Number: " << accountNumber << endl;
cout << "Current Balance: Rs " << balance << endl;
cout << "------------------------" << endl;
}
static void showTotalAccounts()
{
cout << "Total bank accounts: " << totalAccounts << endl;
}
};
// Initialize static member
int BankAccount::totalAccounts = 0;
int main()
{
BankAccount acc1("Rahul Sharma", 5000);
BankAccount acc2("Priya Patel", 10000);
acc1.deposit(2000000);
acc1.withdraw(1000);
acc1.showBalance();
acc2.withdraw(15000000); // Attempting to withdraw more than balance
acc2.showBalance();
BankAccount::showTotalAccounts(); // Calling static function
return 0;
}
*/
//without encapsulation
#include <iostream>
using namespace std;
class Student {
public:
int marks;
};
int main() {
Student s1;
s1.marks = 85; // directly accessing variable
cout << "Marks: " << s1.marks << endl;
return 0;
}
// with encapsulation
#include <iostream>
using namespace std;
class Student {
private:
int marks;
public:
void setMarks(int m) {
marks = m;
}
void displayMarks() {
cout << "Marks: " << marks << endl;
}
};
int main() {
Student s1;
s1.setMarks(85); // setting value through function
s1.displayMarks(); // displaying value
return 0;
}