how to access private data member of class in another class | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

how to access private data member of class in another class

I

27th Jun 2016, 5:36 AM
Prashant Kumar
Prashant Kumar - avatar
3 Answers
+ 1
by friend
27th Jun 2016, 5:58 AM
Nikhil Mishra
Nikhil Mishra - avatar
+ 1
Simplest way is just add the get and set methods for that particular variable. something like this, class test { private: int nPrivate; public: int getValue () { return nPrivate; } void setValue (int nValue) { nPrivate = nValue; } }; class tester { public: void AccessPrivate () { test obj; obj.setValue (65); cout<<obj.getValue(); } }; If you want access private method then use "friend" method.
27th Jun 2016, 6:03 AM
Venkatesh(Venki)
Venkatesh(Venki) - avatar
+ 1
I'd you can, pls use Venkateshs solution. Using the "friend" keyword is less favorable as it gives you direct read *and* write access to all non-const members without a means of copying or preparing the data before it's read / written. Try to use as little access privilege to other classes as possible as the principle of "information hiding" still is *the* mechanism to modularize and decouple software parts.
27th Jun 2016, 9:16 AM
Stefan
Stefan - avatar