Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why don't I have access to the private values of a class through a friend function?

I create a class, and in the class I declare a friend function so that I can later change a private value with an if..else statement, though I can’t even change it without the if..else.

    #include <iostream>
    using namespace std;

    class A {
        
        private:

            float money;
            friend void _setMoney(A a, float i);

        public: 

        void setMoney(float i) {
            money = i;
        };

        float getMoney() {
            return money;
        };

        A(float i) {
            i = money;
        };

    };

    void _setMoney(A a, float i) {
        a.setMoney(i);
    };

    int main(){

        A a(0);

        cout << a.getMoney() << endl;

        a.setMoney(10);

        cout << a.getMoney() << endl;

        _setMoney(a, 20);

        cout << a.getMoney() << endl;
    }

After executing this in VS Code, I get 0, 10, 10 instead of 0, 10, 20.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem is not with _setMoney() being a friend or not. If that were the issue, your code would not even compile.

The real issue is that you are passing the a object in main() by value to _setmoney(), so you are passing in a copy of the object, and are then modifying the copy rather than the original object.

Simply pass the object by reference instead:

void _setMoney(A& a, float i) {
    a.setMoney(i);
};

That being said, A::setMoney() is public, so _setMoney() does not need to be a friend of A in order to call it. Only if _setMoney() wanted to access A::money directly, eg:

void _setMoney(A& a, float i) {
    a.setMoney(i); // <-- friend not required for this
    a.money = i; // <-- friend required for this
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading