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();
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With