Course Content
C++ Introduction
0/1
C++ Variables & Constants
0/1
C++Scope of Variable
0/1
C++ Keywords & Identifiers
0/1
C++ Data Types
0/1
C++ Basic I/O
0/1
C++ Type Conversion
0/1
C++ Operators
0/1
C++ Comments
0/1
C++ If-else
0/1
C++ Ternary Operator
0/1
C++ for Loop
0/1
C++ Ranged for Loop
0/1
C++ while/do-while Loop
0/1
C++ break Statement
0/1
C++ Continue Statement
0/1
C++ switch Statement
0/1
C++ goto Statement
0/1
C++ Functions
0/1
C++ User-defined Functions
0/1
C++ Default Arguments
0/1
C++ Storage Class
0/1
C++ Recursion
0/1
C++ Return by Reference
0/1
C++ Arrays
0/1
C++ Multi-dimentional Arrays
0/1
C++ Arrays & Function
0/1
C++ String
0/1
C++ Structure
0/1
C++ Structure & Functions
0/1
C++ Pointers to Structure
0/1
C++ Pointers
0/1
C++ Void Pointers
0/1
C++ Pointers & Arrays
0/1
C++ Pointers & Functions
0/1
C++ Dynamic Memory Allocation
0/1
C++ OOPs Concepts
0/1
C++ Objects and Class
0/1
C++ Constructors
0/1
C++ Destructors
0/1
C++ Constructor Overloading
0/1
C++ Objects & Function
0/1
C++ Enumeration
0/1
C++ Inheritance
0/1
C++ Inheritance Access Control
0/1
C++ Inheritance Types
0/1
C++ Polymorphism
0/1
C++ Function Overloading
0/1
C++ Function Overriding
0/1
C++ Operator Overloading
0/1
C++ Friend Function
0/1
C++ Virtual Function
0/1
C++ Abstract Class & Pure Virtual Function
0/1
C++ Encapsulation
0/1
C++ Abstraction
0/1
C++ Templates
0/1
C++ Exception Handling
0/1
C++ Multithreading
0/1
C++ Standard Library
0/1
C++ Programming Tutorials
About Lesson

C++ Friend Function and Friend Classes

In this tutorial, we will learn to create friend functions and friend classes in C++ with the help of examples.

Introduction

Data hiding is a fundamental concept of object-oriented programming. It restricts the access of private members from outside of the class.

Similarly, protected members can only be accessed by derived classes and are inaccessible from outside. For example,

class MyClass {
private:
int member1;
}

int main() {
MyClass obj;

// Error! Cannot access private members from here.
obj.member1 = 5;
}

However, there is a feature in C++ called friend functions that break this rule and allow us to access member functions from outside the class.

Similarly, there is a friend class as well, which we will learn later in this tutorial.


friend Function in C++

friend function can access the private and protected data of a class. A friend function can be declared as a global Function as well as a member of another class.
We declare a friend function using the friend keyword inside the body of the class.

class className {
... .. ...
friend returnType functionName(arguments);
... .. ...
}

Example 1: C++ program to demonstrate the working of friend function

#include <iostream>
using namespace std;

class Distance {
    private:
        int kilometer;
        
        // friend function
        friend int addTwo(Distance);

    public:
        Distance() : kilometer(0) {}
        
};

// friend function definition
int addTwo(Distance d) {

    //accessing private members from the friend function
    d.kilometer += 2;
    return d.kilometer;
}

int main() {
    Distance D;
    cout << "Distance in Km: " << addTwo(D);
    return 0;
}

Output

Distance in Km: 2

Here, addTwo() is a friend function that can access both private and public data members.

Though this example gives us an idea about the concept of a friend function, it doesn’t show any meaningful use.

A more meaningful use would be operating on objects of two different classes. That’s when the friend function can be very helpful.


Example 2: C++ Add Members of Two Different Classes using friend functions

#include <iostream>
using namespace std;

// forward declaration
class ClassB;

class ClassA {
    
    public:
        // constructor to initialize num1 to 2
        ClassA() : num1(2) {}
        
    private:
        int num1;
        
         // friend function declaration
         friend int add(ClassA, ClassB);
};

class ClassB {

    public:
        // constructor to initialize num2 to 4
        ClassB() : num2(4) {}
    
    private:
        int num2;
 
        // friend function declaration
        friend int add(ClassA, ClassB);
};

// access members of both classes
int add(ClassA object1, ClassB object2) {
    return (object1.num1 + object2.num2);
}

int main() {
    ClassA object1;
    ClassB object2;
    cout << "Sum of 2 Numbers: " << add(object1, object2);
    return 0;
}

Output

Sum of 2 Numbers: 6

In this program, ClassA and ClassB have declared add() as a friend function. Thus, this function can access private data of both classes.

One thing to notice here is the friend function inside ClassA is using the ClassB. However, we haven’t defined ClassB at this point.

// inside classA 
friend int add(ClassA, ClassB);

For this to work, we need a forward declaration of ClassB in our program.

// forward declaration
class ClassB;

The operator function is called using the obj1 object and obj2 is passed as an argument to the function.


Example 3: C++ friend functions declared as global function

#include <iostream>
using namespace std;
class ABC {

    private:
        int num = 10;
        char ch = 'A';

    public:
        friend void display(ABC obj);
};

// global function
void display(ABC obj) {
    cout << obj.num << endl;
    cout << obj.ch << endl;
}

int main() {
    ABC obj;
    display(obj);

    return 0;
}

Output

10
A

friend Class in C++

A friend class can access private and protected members of other class in which it is declared as friend. This is needed when we want to allow a particular class to access the private and protected members of a class.

We can also use a friend Class in C++ using the friend keyword. For example,

class ClassB;

class ClassA {
   // ClassB is a friend class of ClassA
   friend class ClassB;
   ... .. ...
}

class ClassB {
   ... .. ...
}

When a class is declared a friend class, all the member functions of the friend class become friend functions.

Since classB is a friend class, we can access all members of classA from inside classB.

However, we cannot access members of ClassB from inside classA. It is because friend relation in C++ is only granted, not taken.


Example 4: C++ program to demonstrate the working of friend class

#include <iostream>
using namespace std;

// forward declaration
class ClassB;

class ClassA {
    private:
        int num1;

        // friend class declaration
        friend class ClassB;

    public:
        // constructor to initialize num1 to 2
        ClassA() : num1(2) {}
};

class ClassB {
    private:
        int num2;

    public:
        // constructor to initialize num2 to 4
        ClassB() : num2(4) {}
    
    // member function to add numA
    // from ClassA and numB from ClassB
    int add() {
        ClassA object1;
        return object1.num1 + num2;
    }
};

int main() {
    ClassB object2;
    cout << "Sum: " << object2.add();
    return 0;
}

Output

Sum: 6

Here, ClassB is a friend class of ClassA. So, ClassB has access to the members of classA.

In ClassB, we have created a function add() that returns the sum of num1 and num2.

Since ClassB is a friend class, we can create objects of ClassA inside of ClassB.


Example 5: C++ Passing object as an argument to a friend function

#include <iostream>
using namespace std;
class ABC {

    private:
        char ch = 'A';
        int num = 10;

    public:
        friend class XYZ;
};
class XYZ{
    public:
        void display(ABC obj) {
            cout << obj.ch << endl;
            cout << obj.num << endl;
        }
};

int main() {
    XYZ obj;
    ABC obj2;
    display(obj2);

    return 0;
}

Output

A
10

Features of a Friend Function:

  • The function is not in the scope of the class to which it has been declared as a friend.
  • It cannot be called using the object as it is not in the scope of that class.
  • It can be invoked like a normal function without using the object.
  • It can access the member names directly only by using its object name and dot membership operator with the member name.
  • It can be declared either in the private or the public part.
Exercise Files
No Attachment Found
No Attachment Found
error: Content is protected !!