0% found this document useful (0 votes)
24 views11 pages

Friend Function and Friend Class in C++ (With Examples)

The document explains the concept of friend functions and classes in C++, which allow external functions and classes to access private and protected members of a class. It details the syntax, types, advantages, and disadvantages of friend functions, along with examples demonstrating their usage. Additionally, it contrasts friend functions with friend classes and highlights key points regarding their implementation and limitations.

Uploaded by

Viraj Bhadoria
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views11 pages

Friend Function and Friend Class in C++ (With Examples)

The document explains the concept of friend functions and classes in C++, which allow external functions and classes to access private and protected members of a class. It details the syntax, types, advantages, and disadvantages of friend functions, along with examples demonstrating their usage. Additionally, it contrasts friend functions with friend classes and highlights key points regarding their implementation and limitations.

Uploaded by

Viraj Bhadoria
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction

Data hiding is one of the fundamental concepts of object-oriented programming. It restricts the outside class from accessing
private members. Similarly, protected members are accessible to derived classes and not outside classes.

However, C++ introduces a feature to break this rule. It is known as a friend function in C++ that allows us to access private and
protected member functions from outside the class.

What is a Friend Function in C++?


Global functions in C++ can’t access private class members. However, we may need a global function to access private
members for certain operations without defining it within a class. Hence, we use a friend function in C++ program.

The C++ friend function is a non-member function which is granted special access to private and protected class members. The
function can perform certain operations that need access to private members without defining the function within a class.

Friend functions are not member functions of a class but can access and manipulate private and protected members as they are
declared as friends using the friend keyword within the class body.

Syntax of Friend Function in C++

friend return_type function_name (arguments); // for global function


or
friend return_type class_name::function_name (arguments); // for the member fu

Example of Friend Function in c++

#include <iostream>
using namespace std;

class ATM {
private:
int balance;

public:
ATM(int b) { balance = b; }

friend void checkBalance(ATM a); // Friend function declaration


};

// Friend function definition


void checkBalance(ATM a) {
cout << "Current Balance: $" << a.balance << endl; // Accessing private data
}

int main() {
ATM user(10000);
checkBalance(user); // Friend function accessing private data
return 0;
}

Run Code

Output:

Current Balance: $10000

Explanation:

balance is private, but checkBalance() (friend function) can access it.

Used in banking systems, where an external function needs controlled access to private data.

Types of friend functions in C++


There are two types of friend functions in C++:

1. Global function

2. Member function of another class

1. Global Function

A global function can be declared as a friend function. First, we create a global function and then declare it as a friend function to
a class.

Example:

#include <iostream>
using namespace std;

class Box {
private:
int secretNumber;

public:
Box(int num) : secretNumber(num) {}

// Declaring the global function as a friend


friend void revealSecret(Box b);
};

// Global friend function definition


void revealSecret(Box b) {
cout << "The secret number is: " << b.secretNumber << endl;
}

int main() {
Box myBox(42);
revealSecret(myBox); // Accessing private member using friend function

return 0;
}

Run Code

Output:

The secret number is: 42

Explanation:

1. Private Member: The class Box has a private member secretNumber.

2. Friend Function: The function revealSecret() is declared as a friend inside the class, so it can access secretNumber.

3. Global Scope: The function revealSecret() is defined outside the class.

4. Accessing Private Data: When revealSecret(myBox); is called, it can access and print the private data secretNumber.

2. Member Function of Another Class

C++ allows us to declare a member function of another class as a friend function.

Example:

#include <iostream>
using namespace std;

class Box; // Forward declaration

class Inspector {
public:
void checkSecret(Box b); // Declaring function
};

class Box {
private:
int secretNumber;

public:
Box(int num) : secretNumber(num) {}
// Declaring 'checkSecret' of 'Inspector' class as a friend
friend void Inspector::checkSecret(Box b);
};

// Member function of another class accessing private data


void Inspector::checkSecret(Box b) {
cout << "The secret number is: " << b.secretNumber << endl;
}

int main() {
Box myBox(42);
Inspector inspector;
inspector.checkSecret(myBox); // Accessing private member using friend functi

return 0;
}

Run Code

Output:

The secret number is: 42

Explanation:

1. Forward Declaration: Since Inspector is defined before Box, we use class Box; before Inspector to let it know Box exists.

2. Friend Member Function: The function checkSecret() inside Inspector is declared as a friend inside Box, so it can access
private members.

3. Accessing Private Data: In Inspector::checkSecret(), we access secretNumber even though it’s private in Box.

4. Main Execution: The Inspector object calls checkSecret(myBox), successfully accessing secretNumber.

Features of Friend Function in C++


We can declare a global function or a member function of another class as a friend function.

It is invoked like a regular function without an object or the dot operator. However, we can use the object as an argument
whose value is to be accessed.

This special function can access private and protected data members of a class.

A friend function can be declared anywhere in a class, be it a public or private section of a class.
It may not directly access the protected or private data members and needs an object and the dot operator to access data
members.

It is a non-member function or regular function declared as a friend by using the friend keyword within the class. Once a
function is declared as a friend, it gets all access permissions.

A friend function shouldn’t be a member of the same class.

We use the friend keyword only while declaring a friend function and not while calling or defining it.

It is not restricted to one class and can be a friend to multiple classes.

Example: A Function Friendly to Multiple Classes

#include <iostream>
using namespace std;

class Box; // Forward declaration


class Crate; // Forward declaration

// Global function declaration


void showSum(Box b, Crate c);

class Box {
private:
int secretNumber;

public:
Box(int num) : secretNumber(num) {}

// Declare showSum as a friend


friend void showSum(Box b, Crate c);
};

class Crate {
private:
int hiddenValue;

public:
Crate(int num) : hiddenValue(num) {}

// Declare showSum as a friend


friend void showSum(Box b, Crate c);
};

// Friend function definition


void showSum(Box b, Crate c) {
cout << "Sum of secret numbers: " << b.secretNumber + c.hiddenValue << endl;
}

int main() {
Box myBox(10);
Crate myCrate(20);
showSum(myBox, myCrate); // Accessing private members

return 0;
}

Run Code

Output:

Sum of secret numbers: 30

Explanation:

1. Two Unrelated Classes: Box and Crate have private members secretNumber and hiddenValue.
2. Common Friend Function: The function showSum() is declared as a friend in both classes.

3. Accessing Private Data: Since showSum() is a friend of both classes, it can access secretNumber and hiddenValue to
compute their sum.

4. Execution: Calling showSum(myBox, myCrate); gives the correct sum.

Declaring a Friend Function in C++


We declare a friend function by using the friend keyword inside the class body. Here is the syntax used for the declaration of a
friend function in C++:

// Creating a class named class_Name


class class_Name
{
// declaration of class properties

friend return_type function_Name(Argument_1,...,Argument_5);


}

We declare a function as a friend in C++ inside the class whose data members we need to access. We can define a function
anywhere in the code without using the scope resolution operator.

Example:

#include <iostream>
using namespace std;
class BankAccount {
private:
int balance;

public:
BankAccount(int amount) : balance(amount) {}

// Declaring showBalance as a friend function


friend void showBalance(BankAccount acc);
};

// Friend function definition (outside the class)


void showBalance(BankAccount acc) {
cout << "Account balance: $" << acc.balance << endl;
}

int main() {
BankAccount myAccount(5000);
showBalance(myAccount); // Accessing private member using friend function

return 0;
}

Run Code

Output:

Account balance: $5000

Explanation:

1. Private Member: balance is a private member of BankAccount.

2. Friend Function Declaration: showBalance() is declared as a friend inside BankAccount so it can access balance.
3. Friend Function Definition: The function showBalance() is defined outside the class without a scope resolution operator.

4. Accessing Private Data: showBalance(myAccount); prints the private balance value.

Function Overloading Using Friend Function in C++


Function overloading allows two or more functions to have the same name but different signatures. Hence, the functions will be
different in terms of parameters and return type. These functions are called overloaded functions in C++. Here is an example of
an overloading friend function in C++:

Example:
#include <iostream>
using namespace std;

class Box {
private:
int value;

public:
Box(int v) : value(v) {}

// Declaring overloaded friend functions


friend void display(Box b);
friend void display(Box b, string message);
};

// First overloaded function (no message)


void display(Box b) {
cout << "Box Value: " << b.value << endl;
}

// Second overloaded function (with a message)


void display(Box b, string message) {
cout << message << ": " << b.value << endl;
}

int main() {
Box box1(10);

display(box1); // Calls first function


display(box1, "Stored Number"); // Calls second function

return 0;
}

Run Code

Output:

Box Value: 10
Stored Number: 10

Explanation:

1. Private Member: The class Box has a private member value.


2. Overloaded Friend Functions: Two display() functions are declared as friend inside Box:
One function prints just the value.

The other takes an extra string argument to display a message.

3. Function Calls:
display(box1); → Calls the first function.

display(box1, "Stored Number"); → Calls the second function with a message.

Advantages of C++ Friend Functions


They are used to access all the non-public members of a class.

They enable programmers to create more efficient code.

They can enhance the versatility of overloaded operators as functions can be overloaded as friends.

They offer freedom in regard to the interface, allowing us to use different functions for other classes.

They operate on the instance of both classes and can access private data, serving as a bridge between two classes.

They can access members without requiring them to inherit the class.

They work symmetrically with all friends, which means they work the same way with all classes.

Their added functionality is not commonly used by the class.

A non-member function can share private class information.

They are commonly used when two or more classes have interrelated members related to other parts of a program.

Disadvantages of C++ Friend Functions


They can access private members of a class from outside of a class, violating the rule of data hiding.

We must explicitly declare a function as a friend when inheriting a class from another class.

They can’t perform runtime polymorphism in their members.

They can’t have a storage class specifier, so they can’t be declared static or extern in the code.

What is a Friend Class in C++?


Similar to a friend function in C++, a class can also have a friend class, which has the same privilege. A friend class in C++ can
access the private and protected data members of a class in which it is declared. Hence, all the functions declared within the
friend class can access the private and protected members of the class.

Syntax of C++ Friend Class

We use the following syntax to declare a friend class in C++:


// Creating a class named class_Name.
class class_Name
{
// Declaration of class properties.

friend class friendClassName;


}

friendClassName- The class name declared as a friend.

Friend Class in C++ Example

#include <iostream>
using namespace std;

class BankAccount {
private:
int balance;

public:
BankAccount(int amount) : balance(amount) {}

// Declaring BankManager as a friend class


friend class BankManager;
};

class BankManager {
public:
void showBalance(BankAccount acc) {
cout << "Account balance: $" << acc.balance << endl;
}
};

int main() {
BankAccount myAccount(10000);
BankManager manager;
manager.showBalance(myAccount); // Accessing private balance

return 0;
}

Run Code

Output:
Account balance: $10000

Explanation:

1. Private Member: balance is private inside BankAccount.

2. Friend Class: The BankManager class is declared as a friend inside BankAccount, giving it access to private members.
3. Accessing Private Data: showBalance() inside BankManager can access balance directly.

4. Function Call: manager.showBalance(myAccount); successfully prints the private balance.

Key Points About C++ Friend Functions and Classes


We must use friend functions for limited purposes because declaring a lot of friend functions or classes can lessen the
value of data hiding and encapsulation, which defeats the main purpose of object-oriented programming.

Friendship properties are not inherited, so if a function is declared a friend of a parent class, it doesn't mean it will
automatically become a friend of its child class. To become a friend of the child class, it must be declared as a friend of
that class.

Friendship is not mutual, so if class A is a friend of class B, it doesn’t mean that class B will automatically become a friend
of class A unless declared. So, only class A can access the private data members of class B and not vice-versa.

Difference between a Friend Class and a Friend Function in C++


The following table explains the difference between a friend function and a friend class in C++:

Friend Function Friend Class

We can allow a non-member function We use the friend keyword to allow a class to access
access to private data members using the private data members of another class.
friend function.

We can use it for operator overloading. We use it to create a class over another class.

We must use the forward declaration. We need not use forward declaration, which means we
don’t need to define a class before declaring it as a friend.

You might also like