+ 2

Is regVar in public a variable? Why It has no data type..? And why do we use & before obj(&obj). 'Obj.regvar' i don't get it ?

class MyClass { public: MyClass() { regVar = 0; }; private: int regVar; friend void someFunc(MyClass &obj); }; void someFunc(MyClass &obj) { obj.regVar = 42; cout << obj.regVar; }

13th Feb 2017, 7:28 AM
Black Temple
Black Temple - avatar
3 Respuestas
+ 1
regVar is private and the data type is int as declared after the constructor of MyClass: private: int regVar; &obj means a reference, not to create a new obj. obj.regVar ia setting the regVar, that is inside of MyClass.
15th Feb 2017, 10:04 AM
Felipe Cruz
Felipe Cruz - avatar
+ 1
@felipe cruz but why are we setting this "obj.regvar"? And What exactly is the use of the reference "&obj "
15th Feb 2017, 10:21 AM
Black Temple
Black Temple - avatar
+ 1
Use reference so the system dont create a copy of the original on the memory. As it is just passed as parameter, no need to store the parameter on the memory, just create a reference. &obj is a MyClass type, só when you call "obj.regVar" means you are sending a menssage to set the attribute regVar in (MyClass)obj.
15th Feb 2017, 12:58 PM
Felipe Cruz
Felipe Cruz - avatar