In order to practice a little with friend functions to get accustomed to the concept, I wrote a menial C++ program to check whether encapsulation is preserved by this sort of functions.
Here is the code:
// Friend function
#include<iostream>
using namespace std;
class Friendly {
int a;
public:
// int a; <-- It doesn't work like this, either!
void setA(int new_a);
void display();
friend void encapsulationChecker(Friendly f, int new_a);
};
void Friendly::setA(int new_a) {
a = new_a;
}
void Friendly::display() {
cout << "Value of a: " << a << ".\n";
}
void encapsulationChecker(Friendly f, int new_a) {
f.a = new_a;
}
int main()
{
Friendly f;
f.setA(5);
f.display();
encapsulationChecker(f, 23);
// f.a = 23;
f.display();
return 0;
}
I expected the value of a to be 23, but instead it remains equal to 5. Why does this happen?
Thanks in advance!