Use friend function to access the non-public member variable : Friend « Class « C++






Use friend function to access the non-public member variable

  
#include <iostream>
using namespace std;
class MyClass {
  int a, b;
  public:
    friend int sum(MyClass x);
    void set_ab(int i, int j);
};

void MyClass::set_ab(int i, int j)
{
  a = i;
  b = j;
}

int sum(MyClass object)
{
  return object.a + object.b;
}

int main(void)
{
  MyClass integer;

  cout << "Adding 3 and 4:" << endl;
  integer.set_ab(3,4);
  cout << sum(integer);
}
  
    
  








Related examples in the same category

1.Friend function DemoFriend function Demo
2.Make the inserter into a friend functionMake the inserter into a friend function
3.Define friend function for <<Define friend function for <<
4.friend class for each other
5.Friends can access private members of a class.