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.
We have used the getter and setter method to access the private variables. Here, the setter methods setAge() and setName() initializes the private variables. the getter methods getAge() and getName() returns the value of private variables.
Private variable can declare with the private keyword. In the below example, we will see we can access private variable in the same class. In the below example, we will see we cannot access private variable outside the class.
This is perfectly legal. Objects of the same type have access to one another's private variables. This is because access restrictions apply at the class or type level (all instances of a class) rather than at the object level (this particular instance of a class).
GotW #76 has fascinating language-lawyery details on how to do some of this stuff. :-)
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With