Is there any way I can access Private member variable of a class?
Editing: Not from a member function or friend function but through an instance.
Is there any way I can access Private member variable of a class?
Editing: Not from a member function or friend function but through an instance.
One of the "dirty tricks" of C++ is to do something like:
#define private public
#include "ClassHeader.h"
// now all the private members of the included class are public
I strongly do not recommend that you do this.
You could:
What are you trying to do? If something is private, don't mess with it. It's private for a reason.
Yes. You can access a private member:
While we're proposing bad ideas, there is nothing on the code end which enforces encapsulation -- it's entirely a compiler trick -- so you can write assembly to directly access private members.
But why not just rewrite the base class if it isn't doing what you want already?
Why would you want to?
Visibility rules are clear:
... hence -- if you're writing the class yourself, choose the right visibility. If it's a supplied class, thing carefully why it was made private in the first place...
If you decide to break that rule however, you have several options:
friend
specifierJust cast it around, shift memory and cast back. (didn't compile the code, but you should get the idea).
class Bla
{
public:
Bla() : x(15), str("bla") {}
private:
int x;
std::string str;
}
int main()
{
Bla bla;
int x = *((int*)(&bla));
std::string str = *((std::string*)((int*)(&bla) + 1));
std::cout << x << str;
return 0;
}
Since this is an interview question, I won't go into why you shouldn't do that. :)
EDIT: Classes with virtual functions will have virtual table pointer somewhere there as well. I'm not sure if & will give you address of vt or address of first data member.
Alignment is 4 by default (right?), so if member you are reading does not align, shift by 2 bytes to get to the next one.
GotW #76 has fascinating language-lawyery details on how to do some of this stuff. :-)
I think it depends on how the question is phrased:
Q: How would you access a private member variable? A: I wouldn't.
Along with:
Q: How would you implement ... A: I wouldn't, it's already been done, I'd leverage an existing framework/library.
Interviewers don't always want to know if you can make a wheel, sometimes they are probing to see if you know how to find the nearest service station. :)