21
NovUnderstanding Friend Function in C++
21 Jun 2024
Beginner
1.59K Views
14 min read
Friend Functions in C++
The "friend function" is a feature that provides a means to access a class's private and protected members. Yes, Have you ever thought about how you can grant access, to the protected members of your class in C++ to a specific function or another class? then learning the friend function and also friend class could be useful for you.In this C++ tutorial, we will explore more about "Friend Function and friend Class "including What is a friend function in C++?, the syntax of friend functions in C++, and friend functions in C++ with its examples as well as What is a friend Class in C++?, the syntax of friend Class in C++, and friend Class in C++ with its examples.
1. Explain Friend Function
In C++, a friend function is a function that is not a member of a class but still has access to the class's private and protected members. By declaring a function as a friend, a class can grant it special access privileges, enabling it to operate on the class's internal data.Key characteristics
Let's see the key characteristics of the friend function:
- The function has been declared as a friend, but it is not within the authority of that class.
- Since it is beyond the scope of that class, it cannot be invoked with the object.
- Without requiring the object, it can be called just like any other function.
- It must use an object name and dot membership operator with the member name because it is unable to access the member names directly.
- It can be declared either privately or publicly.
Note: If you want to understand the friend function you have to learn OOPs concepts first. If you have not gone through it yet, just follow the below articles.
Object Oriented Programming Concepts |
Object Oriented Programming (OOPs) Concepts in C++ |
Polymorphism in C++: Types of Polymorphism |
Inheritance in C++ |
Function Overriding in C++ |
Declaration of Friend function
Syntax
Now let's see how to declare a friend function, To declare a friend function, the `friend` keyword is used inside the class definition. The syntax is as follows:
class ClassName {
friend ReturnType FunctionName(Parameters);
// Other members of the class
};
Example 1:Friend Function
Let’s consider an example in the C++ Compiler to understand the concept better.#include <iostream>
using namespace std;
class Square
{
private:
int Height;
public:
Square(): Height(0) { }
friend int printLength(Square); //friend function
};
int printLength(Square b)
{
b.Height += 35;
return b.Height;
}
int main()
{
Square b;
cout<<"Height of Square: "<< printLength(b)<<endl;
return 0;
}
Output
Height of Square: 35
Explanation
- Square Class: This class has one private member called Height. The constructor initializes these members.
- Friend Function: The function printLength is declared as a friend of the Square class, allowing it to access the private members of Square.
- printLength Function: This function takes a Square object as a parameter and computes its volume by accessing its private members.
- Main Function: An object of Square is created with specific dimensions. The height is then calculated using the friend function and printed to the console.
Example 2: Adding members of two different classes using friend functions
// Adding members of two different classes using friend functions
#include <iostream>
using namespace std;
// forward declaration
class ClassB;
class ClassA {
public:
// constructor to initialize numA to 24
ClassA() : numA(24) {}
private:
int numA;
// friend function declaration
friend int add(ClassA, ClassB);
};
class ClassB {
public:
// constructor to initialize numB to 2
ClassB() : numB(2) {}
private:
int numB;
// friend function declaration
friend int add(ClassA, ClassB);
};
// access members of both classes
int add(ClassA objectA, ClassB objectB) {
return (objectA.numA + objectB.numB);
}
int main() {
ClassA objectA;
ClassB objectB;
cout < <"Addition: " < < add(objectA, objectB);
return 0;
}
Output
Addition: 26
Use Cases for Friend Functions
1. Operator Overloading
Friend functions are often used to overload operators, especially when the left operand is not an object of the class.
class Complex {
private:
double real;
double imag;
public:
Complex(double r, double i) : real(r), imag(i) {}
friend Complex operator+(Complex const &, Complex const &);
};
Complex operator+(Complex const &c1, Complex const &c2) {
return Complex(c1.real + c2.real, c1.imag + c2.imag);
}
2. Accessing Multiple Classes
Sometimes, a function needs to access the private data of multiple classes. Making such a function a friend of each class can achieve this.
class A;
class B;
class A {
private:
int dataA;
public:
A() : dataA(0) {}
friend void showData(A, B);
};
class B {
private:
int dataB;
public:
B() : dataB(0) {}
friend void showData(A, B);
};
void showData(A a, B b) {
cout << "Data in A: " << a.dataA << endl;
cout << "Data in B: " << b.dataB << endl;
}
2. Explain Friend Class
- When a class is declared as a friend, it gains access to private and protected members of other classes.
- Allowing a certain class to access members of other classes who are private and protected can be helpful at times.
- For instance, a LinkedList class might be allowed to access Node's secret members.
Declaration of Friend Class
Let's see how to declare a friend class with its syntax.
Syntax
friend class class_name; // declared in the base class
// C++ Program to demonstrate the
// functioning of a friend class
#include
using namespace std;
class ScholarHat {
private:
int private_variable;
protected:
int protected_variable;
public:
ScholarHat()
{
private_variable = 22;
protected_variable = 67;
}
// friend class declaration
friend class Hi;
};
class Hi {
public:
void display(ScholarHat& t)
{
cout << "The value of Private Variable = "
<< t.private_variable << endl;
cout << "The value of Protected Variable = "
<< t.protected_variable;
}
};
int main()
{
ScholarHat s;
Hi fri;
fri.display(s);
return 0;
}
Output
The value of Private Variable = 22
The value of Protected Variable = 67
Explanation
Here, class Hi is declared as a friend inside class ScholarHat. Therefore, Hi is a friend of class ScholarHat. So Class Hican access the private members ofclass ScholarHat.
Advantages and Disadvantages
Advantages
1. Controlled Access
Friend functions provide a controlled way of accessing private and protected data.
2. Flexibility
They offer flexibility in certain designs where non-member functions need access to class internals.
Disadvantages
1. Tight Coupling
Excessive use of friend functions can lead to tighter coupling between classes and functions, reducing modularity.
2. Security Risks
Granting access to private data can expose the class to potential misuse.
Best Practices
1. Limited Usage
- Use friend functions sparingly and only when necessary.
- Excessive use can compromise the principles of encapsulation.
2. Documentation
Clearly document the purpose of each friend function to maintain code readability and maintainability.
3. Design Alternatives
Consider design alternatives like member functions or public interfaces before resorting to friend functions.
Conclusion
Friend functions in C++ are a powerful feature that can provide necessary access to class internals under controlled conditions. They should be used judiciously to balance the benefits of encapsulation and the need for access in certain scenarios. You can take the help of friend functions to create more flexible and efficient C++ programs. Meanwhile, you can also learn other C++ concepts with our self-placed C++ Programming Course.FAQs
A friend function is generally used for accessing the non-public member of a class. A class can allow non-member functions and other classes to access its private data by making them friend. A friend class has complete access to the private data of members of another class without being a member of that class.
A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class.
When it redefines a function of the base class in a derived class with the same signature i.e., name, return type, and parameter but with a different definition, it is called function overriding.