If a pointer is supposed to be passed, why is the friend function's argument (MyClass &obj), not (MyClass *obj) ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

If a pointer is supposed to be passed, why is the friend function's argument (MyClass &obj), not (MyClass *obj) ?

3rd Jan 2016, 2:01 PM
Tesik
3 Answers
+ 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.
19th Jun 2016, 5:43 PM
Reddy Jahnavi Tenepalli
Reddy Jahnavi Tenepalli - avatar
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).
16th Jan 2016, 5:23 PM
Sergio Sanchez
Sergio Sanchez - avatar
0
Beacuse we need to send memory address of the object. And hence ampersant is used which indicates "address of"
11th Apr 2016, 2:24 PM
SRI CHANDRA REDDY NAKKA
SRI CHANDRA REDDY NAKKA - avatar