Arvind Patel
Arvind Patel

Reputation: 53

Using friend function, can we overwrite the private member of the class?

In the given c++ code the private member of class DEF is getting initialized in the constructor and again inside the friend function. So the redefinition will overwrite the private variables or the value given by the constructor will persist?

#include<iostream>

//class DEF;

class ABC{
        public:
                 int fun(class DEF);
};

class DEF{
        private:
                int a,b,c;

        public:
        DEF():a(1),b(12),c(2){}
        friend  int ABC::fun(class DEF);/*Using friend function to access the private member of other class.*/
        void fun_2();
};

void DEF::fun_2(){
        cout<<"a : "<<&a<<' '<<"b : "<<&b<<' '<<"c: "<<&c<<endl;
        cout<<"a : "<<a<<' '<<"b : "<<b<<' '<<"c: "<<c<<endl;
}

int ABC::fun(class DEF A){
        A.a = 10;
        A.b = 20;
        A.c = 30;

        int data = A.a + A.b + A.c;
        cout<<"a : "<<&(A.a)<<' '<<"b : "<<&(A.b)<<' '<<"c: "<<&(A.c)<<endl;
        cout<<"a : "<<A.a<<' '<<"b : "<<A.b<<' '<<"c: "<<A.c<<endl;
        return data;
}

int main(){
        cout<<"Inside main function"<<endl;
        ABC obj_1;
        DEF obj_2;
        obj_2.fun_2();
        int sum = obj_1.fun(obj_2);
        cout<<"sum : "<<sum<<endl;
        obj_2.fun_2();

}

Upvotes: 5

Views: 811

Answers (1)

Mohit Jain
Mohit Jain

Reputation: 30489

In below line:

int ABC::fun(class DEF A)

You are passing argument by value and thus value of local object is changed.

To ensure the values persist, pass the value by reference as:

int ABC::fun(DEF &A)
//               ^   <-- class is superfluous here

Upvotes: 2

Related Questions