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
.
NO you can't, atleast not in a portable way approved by the C++ standard.
If you have members under a Private access specifier then those members are only accessible from within the class. No outside Access is allowed.
An Source Code Example:
A Workaround:
friend
to rescueTo access the private member, you can declare a function/class as friend of that particular class, and then the member will be accessible inside that function or class object without access specifier check.
Modified Code Sample:
http://bloglitb.blogspot.com/2010/07/access-to-private-members-thats-easy.html
this guy's blog shows you how to do it using templates. With some modifications, you can adapt this method to access a private data member, although I found it tricky despite having 10+ years experience.
I wanted to point out like everyone else, that there is an extremely few number of cases where doing this is legitimate. However, I want to point out one: I was writing unit tests for a software suite. A federal regulatory agency requires every single line of code to be exercised and tested, without modifying the original code. Due to (IMHO) poor design, a static constant was in the 'private' section, but I needed to use it in the unit test. So the method seemed to me like the best way to do it.
I'm sure the way could be simplified, and I'm sure there are other ways. I'm not posting this for the OP, since it's been 5 months, but hopefully this will be useful to some future googler.
access private members outside class ....only for study purpose .... This program accepts all the below conditions "I dont want to create member function for above class A. And also i dont want to inherit the above class A. I dont want to change the specifier of iData."
//here member function is used only to input and output the private values ... //void hack() is defined outside the class...
Bad idea, don't do it ever - but here it is how it can be done:
There's no legitimate way you can do it.
Start making
friend
s ofclass A
. e.g.Edit:
If you can't change
class A
body thenA::iData
is not accessible with the given conditions in your question.