Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();

}
like image 635
Arvind Patel Avatar asked Oct 30 '22 06:10

Arvind Patel


1 Answers

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
like image 128
Mohit Jain Avatar answered Nov 15 '22 05:11

Mohit Jain