1️⃣ Overview
A friend class can not only access private members but also modify them. This is useful when an external class needs to control or update private data without modifying the main class structure.
2️⃣ Example: Modifying Private Members Using a Friend Class
#include <iostream>
using namespace std;
class Account {
private:
string owner;
double balance;
public:
Account(string o, double b) {
owner = o;
balance = b;
}
// Declare Friend Class
friend class BankManager;
};
class BankManager {
public:
// Function to update balance
void updateBalance(Account &acc, double newBalance) {
acc.balance = newBalance; // Modifying private member
}
// Function to display account details
void showDetails(Account acc) {
cout << "Owner: " << acc.owner << endl;
cout << "Balance: $" << acc.balance << endl;
}
};
int main() {
Account acc("Alice", 5000.75);
BankManager manager;
cout << "Before Update:" << endl;
manager.showDetails(acc);
manager.updateBalance(acc, 7500.50); // Changing private value
cout << "\nAfter Update:" << endl;
manager.showDetails(acc);
return 0;
}
🔹 Output
Before Update:
Owner: Alice
Balance: $5000.75
After Update:
Owner: Alice
Balance: $7500.50
3️⃣ How This Works?
✔ The BankManager
class is a friend of Account
, so it can access & modify private members.
✔ The updateBalance
function changes the private balance
variable.
✔ The friend class maintains control over private data without exposing it publicly.
4️⃣ Another Example: Changing Private Values in Student Class
#include <iostream>
using namespace std;
class Student {
private:
string name;
int marks;
public:
Student(string n, int m) {
name = n;
marks = m;
}
friend class Teacher; // Friend class declaration
};
class Teacher {
public:
void updateMarks(Student &s, int newMarks) {
s.marks = newMarks; // Changing private member
}
void display(Student s) {
cout << "Student Name: " << s.name << endl;
cout << "Marks: " << s.marks << endl;
}
};
int main() {
Student s("John", 80);
Teacher t;
cout << "Before Update:" << endl;
t.display(s);
t.updateMarks(s, 95); // Modifying private marks
cout << "\nAfter Update:" << endl;
t.display(s);
return 0;
}
🔹 Output
Before Update:
Student Name: John
Marks: 80
After Update:
Student Name: John
Marks: 95
5️⃣ Key Takeaways
✔ Friend classes can modify private values of another class.
✔ Useful for external control & data management (e.g., Bank, Student, Employee).
✔ Avoid overuse as it breaks encapsulation.
Would you like an example with multiple friend classes? 🚀
0 Comments