Why the someFunc() has obj as parameter but not &obj in the main . | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why the someFunc() has obj as parameter but not &obj in the main .

10th Nov 2020, 2:39 PM
VAIBHAV KUMAR
VAIBHAV KUMAR - avatar
5 Answers
+ 3
This is called passing by reference. While calling the method inside main() you just pass the argument to it and in the actual method definition you use a reference of that argument as a parameter by preceding it with &. In this way you do not create a copy of the argument but get the reference and make modifications. So any modifications made inside the method will be reflected to the one inside the main().
10th Nov 2020, 4:18 PM
Avinesh
Avinesh - avatar
+ 2
class MyClass { public: MyClass() { regvar = 0; } private: int regVar; friend void someFunc(MyClass &obj); }; void someFunc(MyClass &obj) { obj.regVar = 42; cout << obj.regVar; } Int main(){ Myclass obj; SomeFunc(obj); } //outputs : 42
10th Nov 2020, 3:11 PM
VAIBHAV KUMAR
VAIBHAV KUMAR - avatar
+ 1
If you are talking about passing a var by address Then it will be like this Type SomeFun(type *Name) Then in main() SomeFun(&SomeVar) *This is C++ format
10th Nov 2020, 2:56 PM
Muhammad Atif Waheed
Muhammad Atif Waheed - avatar
+ 1
Mention the language and share the piece of code that you do not understand.
10th Nov 2020, 3:06 PM
Avinesh
Avinesh - avatar
0
Please clear your question
10th Nov 2020, 2:53 PM
Muhammad Atif Waheed
Muhammad Atif Waheed - avatar