tags:

views:

342

answers:

9

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.

A: 

Yes why not , through a member function

sameer karjatkar
+4  A: 

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.

Greg Hewgill
hahahahaha that's gold
Nick Bedford
Although you have added the disclaimer, some things just shouldn't be handed out... it makes it too easy for the crazy people to do it.
Michael Aaron Safyan
Section 17.4.3.1.1 of the C++ Standard: "Nor shall such a translation unit define macros for names lexically identical to keywords." Of course, no known compiler rejects such programs.
Dietrich Epp
Even for compilers that allow it, this violates ODR, and results in undefined behaviour. :-P
Chris Jester-Young
@Michael, and once the crazies reveal themselves we can get them the medications they need.
Jason D
Heh. Once I saw "#define const".
kyoryu
+4  A: 

You could:

  1. Place the private members in the public section
  2. Make your class or function a friend of the class.
  3. Provide an accessor to the data.
  4. Take the address of the class, add the offset to that variable, cast, and dereference. (Yuck)

What are you trying to do? If something is private, don't mess with it. It's private for a reason.

GMan
IMHO, the fourth one's the best :)
hab
+2  A: 

Yes. You can access a private member:

  • ...within other instances of the same (exact) type.
  • ...within classes or functions declared to be a friend of that class.
  • ...via a public accessor (getter/setter) member function.
Michael Aaron Safyan
+2  A: 

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?

Conspicuous Compiler
+2  A: 

Why would you want to?

Visibility rules are clear:

  • private methods are to be accessed only by methods of the class
  • protected methods can be accessed by methods of the class or descendants
  • public methods can be accessed by anyone

... 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:

  • you can befriend the class that ought to access the private methods via a friend specifier
  • you can use an ugly preprocessor hack that probably someone posted already, but do it only if you need to use the fields or methods to do unit-testing -- any other use is bad design
  • you can use an ugly type-casting hack, but it's so ugly that I'm afraid to even post it not to get downvoted ;>
Kornel Kisielewicz
Anonymous cowardly down-voting?
Kornel Kisielewicz
Probably the OP. He seems to down-vote all the correct answers: "don't."
GMan
+4  A: 

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.

Eugene
Might not work if the class has any virtual functions.
zr
It's possible for an optimizer to rearrange the allocation order of private members, so this isn't guaranteed to work.
David Lively
+12  A: 

GotW #76 has fascinating language-lawyery details on how to do some of this stuff. :-)

Chris Jester-Young
That template trick is awesome, but needs the class to have something templated.
Eugene
@Chris, ehh, can't beat you if you're referencing GotW :>
Kornel Kisielewicz
My preference goes to the macro trick, just so easy...
Matthieu M.
A: 

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. :)

Duncan