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
  int x;
  int y;
  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;
  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.