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