+ 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 ?
11 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/
+ 9
Use Pointers đ
+ 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.
+ 6
yeah
+ 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..
+ 3
use getters and setters to get and set them
+ 3
Me!
+ 1
you cant.
+ 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;
}
+ 1
through public functions