The concept of encapsulation and data hiding indicate that nonmember functions should not be able to access an object’s private and protected data. The policy is if you are not a member, you can’t get it. But there is a certain situation wherein you need to share your private or protected data with nonmembers. ‘Friends’ come here as a rescue.

A friend class is a class whose member functions can access another class’ private and protected members. Ex.:

class ABC
{
private:
  int x;
  int y;
public:
  void getvalue(void)
  {
    cout << "Enter the values : ";
    cin >> x >> y;
  }
  friend float avg(ABC A);
};
float avg(ABC A)
{
  return float(A.x + A.y)/2.0;
}
int  main()
{
  ABC obj;
  Obj.getvalue();
  float av;
  av = avg(obj);
  cout << "Average = " << av;
  return 0;
}

About our authors: Team EQA

You have viewed 1 page out of 62. Your C++ learning is 0.00% complete. Login to check your learning progress.

#