1. Friend Function in C++
Understanding Access Privileges
Beyond Class Boundaries
Presented by: [Your Name]
2. Introduction
• C++ supports Encapsulation by restricting
access to class members.
• But sometimes, we need external functions to
access private or protected members.
• This is where friend functions come in.
3. What is a Friend Function?
• A friend function is a non-member function
that is granted access to the private and
protected members of a class.
• Declared using the keyword 'friend' inside the
class.
4. Syntax
• class ClassName {
• friend returnType
functionName(arguments);
• };
• Declared inside the class with 'friend'
keyword.
• Defined outside the class like a regular
function.
5. Example Code
• class Box {
• private:
• int length;
• public:
• Box(int l) : length(l) {}
• friend void printLength(Box b);
• };
• void printLength(Box b) {
6. Key Points
• Friend function is not a member of the class.
• Can be declared in one or more classes.
• Can be a normal function, a friend class, or an
operator overload.
7. Use Cases
• When two or more classes need to access
each other's private data.
• For operator overloading (especially <<, >>, +,
etc.)
• When a non-member needs special access
privileges.
8. Friend Function vs Member
Function
• Aspect | Friend Function | Member
Function
• ----------------|----------------------|--------------------
----
• Belongs to | Outside class | Inside class
• Access private | Yes (if friend) | Yes
• Called using | Object as argument | Object
directly
10. Summary
• Friend functions provide controlled access to
private data.
• Must be used sparingly to maintain
encapsulation.
• Useful for operator overloading and external
utilities.