Home > database >  Can't change the value of private member of a class using friend class
Can't change the value of private member of a class using friend class

Time:10-22

So I was trying to learn how to change the value of the private class member using friend class, but the friend class cannot change the value of the main class, here is the code I have done, I am new in the world of coding, please help me out :)

#include <iostream>
using namespace std;

class A {
private:
    int marks;
    
    public:
    show_marks()
    {
        cout <<marks;
    }
    set_marks( int num )
    {
        marks =num;
    }
    
    
    friend class B;

};
class B{

    public:
    
    show_A_marks(A teacher, int num){
    teacher.marks= num;
    }
};
int main(){
    A teacher;
    teacher.set_marks(10);
     teacher.show_marks();

     cout <<endl;
     
     B student;
     student.show_A_marks(teacher,20);
     teacher.show_marks();
}

-This was supposed to print: 10 20 but is printing: 10 10

CodePudding user response:

In the function:

show_A_marks(A teacher, int num)

You are passing teacher by value. You are making a copy of the value, and editing that copy. When the function returns, the copy is gone. You need to pass it by reference:

show_A_marks(A& teacher, int num)
//            ^ reference to A

see What's the difference between passing by reference vs. passing by value? for more info.

  • Related