Using a friend function, is it possible to overwrite a private member of a class?

In this C ++ code, the private member of the DEF class is initialized in the constructor and again inside the friend function. So, redefinition will overwrite private variables or the value set by the constructor will be saved?

#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){ Aa = 10; Ab = 20; Ac = 30; int data = Aa + Ab + Ac; cout<<"a : "<<&(Aa)<<' '<<"b : "<<&(Ab)<<' '<<"c: "<<&(Ac)<<endl; cout<<"a : "<<Aa<<' '<<"b : "<<Ab<<' '<<"c: "<<Ac<<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(); } 
+5
source share
1 answer

In the line below:

 int ABC::fun(class DEF A) 

You pass an argument by value and therefore the value of the local object changes.

To make sure that the values are saved , pass the value by reference as:

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

Source: https://habr.com/ru/post/1245756/


All Articles