This question already has an answer here:
I have a class A
as mentioned below:-
class A{
int iData;
};
I neither want to create member function nor inherit the above class A
nor change the specifier of iData
.
My doubts:-
- How to access
iData
of an object sayobj1
which is an instance ofclass A
? - How to change or manipulate the
iData
of an objectobj1
?
Note: Don't use friend
.
You can't. That member is private, it's not visible outside the class. That's the whole point of the public/protected/private modifiers.
(You could probably use dirty pointer tricks though, but my guess is that you'd enter undefined behavior territory pretty fast.)
iData
is aprivate
member of the class. Now, the wordprivate
have a very definite meaning, in C++ as well as in real life. It means you can't touch it. It's not a recommendation, it's the law. If you don't change the class declaration, you are not allowed to manipulate that member in any way, shape or form.Here's a way, not recommended though
It's possible to access the private data of class directly in main and other's function...
here is a small code...
In C++, almost everything is possible! If you have no way to get private data, then you have to hack. Do it only for testing!
friend is your friend.
If you're doing this regularly you should probably reconsider your design though.