Friend Classes and Functions
Friend Classes and Functions
classes
Introduction to Friendship in
OOP
What is Friendship?
A concept that allows a function or class to access private and protected
members of another class.
Used to enable special relationships between classes or functions.
Why Use Friendship?
When external functions or classes require tightly coupled interactions with
the internals of another class.
Friend Functions - Definition
Friendship is Limited:
Friendship is not mutual (not bidirectional) and not inherited by derived classes.
Encapsulation Violation:
Use sparingly to avoid breaking the encapsulation principle; prefer public methods
like getters/setters.
Explicit Friendship:
Friendship must be explicitly granted by the class, not assumed by the function.
Global Nature:
Friend functions are global, behaving like regular functions but with special access.
Common Use Cases:
Operator overloading.
Utility functions requiring access to private data (e.g., comparing or combining
objects).
Friend Class
public:
ClassA() : privateMember(100) {}
};
class ClassB {
public:
void accessClassA(ClassA obj) {
cout << "Accessing private member of ClassA: " << obj.privateMember << :endl;
}
};
Scenario 1
Two classes, ClassA and ClassB, need to access each other's private
data. ClassB is declared as a friend of ClassA, so it can access its
private members.
Scenario 2
You are designing a time management system where you need to add
two time durations. Each time object stores hours, minutes, and
seconds as private data members. However, you don’t want to
expose these details directly through public getters. A friend
function is used to add two time objects by directly accessing their
private data members.
Scenario 3
You are designing a time management system where you need to add
two time durations. Each time object stores hours, minutes, and
seconds as private data members. However, you don’t want to
expose these details directly through public getters. A friend
function is used to add two time objects by directly accessing their
private data members.
Scenario 4