+ 2
If a pointer is supposed to be passed, why is the friend function's argument (MyClass &obj), not (MyClass *obj) ?
3 Antworten
+ 2
pass by reference and pass by address both are different. in pass by address,we pass the address as parameter,and argument of called function is pointer. But in case of pass by reference the parameter is a object of type class.p(here p is obj of class).argument of called function is &a.(a is a variable)
here '&' does not refer to address. we are just passing reference of object to the called function. We use pass by reference in most cases because there is no need of pointer(which we use in pass by address)and no need of creating a copy of variable(which we do in pass by value)
#include<iostream>
class Myc
{ private:
int m_month;
friend int get(Myc &b);
};
void get(Myc &b)
{
obj.m_month=0;//sets value to 0
}
int main()
{
Myc obj;
obj.get(9);//resets value to 9
}
I hope this ans helps.
0
Hmm...I'm guessing because you want to refer to the object (refer to its address), rather than the contents of the object. "*obj" would--generally speaking--would be declaring a "new" object (in this case)..which is not what we want, we want to pass the "already constructed object" of the befriended class so that we can access its member variable(s).
0
Beacuse we need to send memory address of the object. And hence ampersant is used which indicates "address of"