0

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!

Frank
  • 19
  • 3

2 Answers2

1

The friendly instance f is passed by value to encapsulationChecker. So the copied f is modified, not the one in the caller.

You need

void encapsulationChecker(Friendly& f, int new_a) {

That is, pass the f by reference.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

You're passing the argument by value, which means it's copied into the function. If your intention is to take the same value by reference, you indicate that with an & after the type.

void encapsulationChecker(Friendly& f, int new_a) {
    f.a = new_a;
}

Note that our argument type is declared Friendly&, not Friendly, to get an lvalue reference.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
  • Hi, Silvio, thanks for both your response and @Bathsheba 's. I'm not very far along my learning process so I actually don't know why your solution works, but it does. – Frank Sep 20 '22 at 14:50
  • @Frank [A more general explanation of pass by value and pass by reference](https://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value). C++ falls under the "Older Languages" category and follows the traditional definition for everything but arrays, which [decay to pointers](https://stackoverflow.com/questions/1461432/what-is-array-to-pointer-decay) and require tricks to pass by value. – user4581301 Sep 20 '22 at 15:13
  • Thanks to everybody for the resources and explanations provided, I will certainly make good use of them. Coming from Java I must say going back to C-ish programming is a bit painful! – Frank Sep 21 '22 at 08:09