Curriculum
Course: Learn C++
Login

Curriculum

Learn C++

Text lesson

Introduction to Friend Function in C++

In this lesson, you will learn

  • Need of a Friend Function
  • Friend Function
  • Example

 

Need of a Friend Function

We know that the private members can not be accessed outside the class i.e. a non-member function can not have access to the private data of a class.

However, there is a situation where you would like to provide access to unrestricted(private) data of a class to the outside member (non-member).

This can be achieved using friend functions or friend classes.

 

Example: Doctor-Patient Confidentiality

Imagine two classes representing a Doctor and a Patient. The Patient class contains sensitive medical information as private data members, which should not be accessible directly. However, the Doctor class needs access to this information to provide proper medical care.

So we would like to use the function ExaminePatient() to operate on the objects of both classes. In such a scenario, C++ allows the common function to be made friendly with both classes and allows the function to access their private data.

 

What is the Friend Function

  • A friend function is a function that is not a member of a class but is granted special access to the private and protected members of that class.
  • Friend functions are declared using the friend keyword within the class definition.
  • It can be useful in specific situations where you need to access or modify the private or protected data members of a class, but you don’t want to make those members public.

Syntax of Friend Function

class MyClass {
private:
    -------------
    -------------
public:
    -------------
    friend void DisplayPrivateData();//friend function declaration
};

 

Example 1: Access Private Data using Friend Function

//FriendFuncEx1.cpp
#include <iostream>
using namespace std;

class Sample {
private:
    int data;

public:
    Sample(int d) : data(d) {}

    friend void DisplayData(Sample& obj);//friend function declaration
};

void DisplayData(Sample& obj) {
    cout<< "Private Data: " <<obj.data <<endl;
}

int main() {
    Sample s(42);
    DisplayData(s); // Access privateData using a friend function
    return 0;
}

 

Output

Private Data: 42

 

In this example, the DisplayData function is a friend of the Sample class, allowing it to access and display the private data member data.

Note: Like member functions, a friend function can not access the members directly and has to use an object name and dot operator to access each member. So usually it takes an object as an argument.

 

Example 2: Accessing Private Data

//FriendFuncEx2.cpp
#include <iostream>
using namespace std;

class Student {
private:
    int marks1,marks2,marks3;
public:
    void SetMarks(){
        marks1=75;marks2=80;marks3=65;
    }
    //friend function declaration
    friend float average(Student alice);
};

float average(Student alice){
    return float(alice.marks1+alice.marks2+alice.marks3)/3.0;
}

int main(){
    Student s;
    s.SetMarks();
    cout<<"Average marks: "<<average(s);
}

 

Output

Average marks: 73.3333

 

Important Points!

1. A member function of one class can be the friend function of another class. In this case, the function is defined using the scope resolution operator(::).

Syntax

class B{
    ---------
    public:
        int AccessData(); // Member function of B
    ---------
};

class A{
    private:
       int data;
    ---------
    public:
       friend int B :: AccessData(); //AccessData() of Class B
       ---------                    //is friend of Class A
                                   //Class B can access private data of Class A
}

 

2. We can also declare a complete class as a friend class if you want to declare all member functions of a class as a friend function.

class ClassA
{
     -----------
     public: 
         friend class ClassB; // ClassB is a friend of ClassA 
         -----------        
}

 

Note: Here, ClassB is a friend of ClassA. Since ClassB becomes the friend class, it will have access to all the public, private, and protected members of ClassA.

However, the opposite will not be true. Hence, ClassA will not have access to private members of ClassB.

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review

 

 


Warning: Undefined array key "student_url_profile" in /var/www/wp-content/plugins/masterstudy-lms-learning-management-system/_core/lms/helpers.php on line 1340

Warning: Undefined array key "student_url_profile" in /var/www/wp-content/plugins/masterstudy-lms-learning-management-system/_core/lms/helpers.php on line 1345