How can we access private data members of a class from outside the class without using friend functions ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

How can we access private data members of a class from outside the class without using friend functions ?

How can we access private data members of a class from outside the class without using friend functions ?

7th Aug 2018, 1:55 AM
nirmites
nirmites - avatar
10 Answers
+ 14
Thats easy. - You can't. That is the purpose of a private attribute, to protect the data. https://www.sololearn.com/learn/CPlusPlus/1713/
7th Aug 2018, 2:30 AM
Manual
Manual - avatar
+ 9
Use Pointers 😄
11th Aug 2018, 9:58 AM
Real Gutch
Real Gutch - avatar
+ 8
Hi everybody, Let me disagree with all the answer above. Actually, there are ways to directly access private members of a class. Spoiler: pointers. If you know the class well and what is the order of the members, you can use pointers and casting to gain access to private members. See this simple code: https://code.sololearn.com/cQfJsubvXuuO/?ref=app As you can see, I can manipulate the members of a class provided I have enough information about them. So, the correct answer is: it depends!! On what? Object knowledge. Now if you want the correct way: just as mentioned before: use getters and setters.
7th Aug 2018, 12:23 PM
Mark
+ 6
yeah
14th Aug 2018, 8:30 AM
Real Gutch
Real Gutch - avatar
+ 5
Mark , correct... I changed private member as below and hence not worked as expected: int a,value; obviously, we should not violate...but yes, something new I learnt today... tanks for posting this..
7th Aug 2018, 2:15 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 3
use getters and setters to get and set them
7th Aug 2018, 10:13 AM
Salifu Gebilila
Salifu Gebilila - avatar
+ 3
Me!
7th Aug 2018, 12:40 PM
Adriana(Addy)#be Crazy
Adriana(Addy)#be Crazy - avatar
+ 1
you cant.
7th Aug 2018, 3:34 AM
Nezumi Neko
Nezumi Neko - avatar
+ 1
well im working on a database right now and i find set-get helpful as accessors: class Parts { public: Parts(); void setPartsName(std::string inPartsName); std::string getPartsName() const; void setBrandName(std::string inBrandName); std::string getBrandName() const; void setPartsNumber(int inPartsNumber); int getPartsNumber() const; void setPartsPrice(int NewPrice); int getPartsPrice() const; bool getIsAdded() const; protected: std::string mPartsName; std::string mBrandName; int mPartsNumber; int mPartsPrice; bool bAdded; }
8th Aug 2018, 4:43 PM
kojiro
+ 1
through public functions
14th Aug 2018, 6:17 AM
Lisa
Lisa - avatar