Reputation: 3277
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.
Upvotes: 9
Views: 3255
Reputation: 2094
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. :)
Upvotes: 0
Reputation: 7258
Just 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.
Upvotes: 5
Reputation: 57555
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
specifierUpvotes: 2
Reputation: 6469
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?
Upvotes: 2
Reputation: 95499
Yes. You can access a private member:
Upvotes: 3
Reputation: 503855
You could:
What are you trying to do? If something is private, don't mess with it. It's private for a reason.
Upvotes: 5
Reputation: 993095
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.
Upvotes: 5