Advantages of using friend classes - C++

Explain the advantages of using friend classes.

There are situations when private data members need to be accessed and used by 2 classes simultaneously. In these kind of situations we can introduce friend functions which have an access to the private data members of both the classes. Friend functions need to be declared as ‘friend’ in both the classes. They need not be members of either of these classes.

What are friend classes? Explain its uses with an example.

A friend class and all its member functions have access to all the private members defined within other class.
#include <iostream>
using namespace std;
class Numbers
   int a;
   int b;
       Numbers(int i, int j)
          a = i;
          b = j;
       friend class Average;

class Average
       int average(Numbers x);

int Average:: average(Numbers x)
   return ((x.a + x.b)/2);

int main()
   Numbers ob(23, 67);
   Average avg;
   cout<<”The average of the numbers is: ”<<avg.average(ob);
   return 0;
Guideline that should be followed while using friend function
Guideline that should be followed while using friend function - When the application is needed to access a private member of another class, the only way is to utilize the friend functions.....
What is Polymorphism? - C++
What is Polymorphism? - Polymorphism means the ability to take more than one form. An operation may exhibit different behavior in different instances....
What is Inheritance? - C++
What is Inheritance? - Inheritance: One of the most important features of OO design is code-reusability......
Post your comment