C++ Friend Function & Classes

C++ Friend Function & Classes

C++ Friend Function & Classes One of the most important concepts of object-oriented programming is data hiding, i.e., a nonmember function cannot access the class object’s related private or protected data. But, sometimes this restriction may force the programmer to write long and complex codes. So, there is a mechanism built in C++ programming to access private or protected data from non-member functions. This is done using a friend function or a friend class.

C++ Friend Function

When we defined a function as a friend to a class then, the private and protected data of a class can be accessed using that function. The compiler knows a given function is a friend function by the use of the keyword friend.

For accessing the data, the declaration of a friend function should be made inside the body of the class, it can be anywhere inside class either in private or public part starting with keyword friend.

Declaration of friend function in C++

class class_name
{
   ... .. ...
   friend returnType functionName(argument's);
   ... .. ...
}

Now, you can define the friend function as a normal function to access the data of the class. No friend keyword is used in the definition.

returnType functionName(argument/s)
{
... .. ...
// Private and protected data of className can be accessed from
// this function because it is a friend function of className.
... .. ...
}

Working with friend Function

/* C++ program to demonstrate the working of friend function.*/
#include <iostream> 
using namespace std; 
class student 
{ 
    private: 
        int rno; 
        char name[30]; 
        float m1,m2,m3; 
        float total,avg; 
        char grade; 
    public: 
        void getdata(); 
        void display(); 
        friend void calculate(student&); 
}; 
void student::getdata() 
{ 
    cout<<"Enter Rno,Name,M1,M2,M3: "; 
    cin>>rno>>name>>m1>>m2>>m3; 
} 
void student::display() 
{ 
    cout<<"Roll No = "<<rno<<endl; 
    cout<<"Name = "<<name<<endl; 
    cout<<"M1 = "<<m1<<endl; 
    cout<<"M2 = "<<m2<<endl; 
    cout<<"M3 = "<<m3<<endl; 
    cout<<"Total ="<<total<<endl; 
    cout<<"Average = "<<avg<<endl; 
    cout<<"Grade = "<<grade<<endl; 
} 
void calculate(student& s) 
{ 
    s.total=s.m1+s.m2+s.m3; 
    s.avg=s.total/3; 
    if(s.avg>=60) 
    { 
        s.grade='A'; 
    } else 
    { 
        if(s.avg>=50) 
        { 
            s.grade='B'; 
        } else 
        { 
            s.grade='C'; 
        } 
    }
}
int main() 
{ 
    student s1; 
    s1.getdata(); 
    calculate(s1); 
    s1.display(); 
    return 0; 
}

Output:

Enter Rno,Name,M1,M2,M3: 12 Balu 78 69 98                                                                                                                    

Roll No = 12                                                                                                                                                 
Name = Balu      

M1 = 78                                                                                                                                                      

M2 = 69                                                                                                                                                      
M3 = 98                                                                                                                                                      
Total  =245                                                                                                                                                  
Average = 81.6667                                                                                                                                            
Grade = A  

Here, friend function calculate() is declared inside student class. So, private data can be accessed from this function.

Though this example gives you an idea about the concept of a friend function, Here, calculate() method calculates total, avg, and grade of student object and returns back to main() method.

C++ Friend Class

Friend class is similar to a friend function, a class can also be made a friend of another class using keyword friend. When a class is made as a friend to another class, all the member and member functions can access to friend class.

Working with friend Class

/* C++ program to demonstrate the working of friend class.*/
#include <iostream>
using namespace std;

class B; // forward declaration of class B is optiona
class A
{
    private:
     int income1;
     int income2;
    public:
     void setdata(int in1,int in2)
     {	
         income1=in1;
         income2=in2;     
     }
     friend class B;   // class B can access private data of class A.
};

class B
{   private:
      int income;  //income is private data member.
   public:
      int funcB(A a1)
      {	 
          return (a1.income1+a1.income2);      
      }
      void setdata(int in)
      {
          income=in;      
      }
      void show()
      {	
          A a1;
          a1.setdata(100,200);
          cout<<"A's Income1 in show(): "         <<a1.income1<<endl;
          cout<<"B's income in show(): " <<income<<endl;      
      }
};

int main()
{ 
    A a1;
    B b1;
    a1.setdata(500,1000);
    b1.setdata(300);
    cout<<"A a1 total income: "<<b1.funcB(a1)<<endl;
    b1.show();
    
    return 0;
}

Output:

A a1 total income: 1500                                                                                                                                      
A’s Income1 in show(): 100                                                                                                                                   
B’s income in show(): 300

whatsapp

error: Content is protected !!