Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing private members [closed]

Is it appropriate to access a class' private members by casting it to a void pointer and then to a struct?

I don't think I have permissions to modify the class that contains the data members that I need to access. I don't want to take a risk accessing the data members in an indirect way if it is not ethical.

EDIT: Had to edit this further... I am pretty sure the class wouldn't be modified, so it's ok to that extent... my only concern is, if the person who coded that class gets to know of this, it might not go down well with him :(.

like image 985
Shree Avatar asked Apr 07 '09 14:04

Shree


2 Answers

I have had this happen to me since there was a very crappy source control system in place where for old versions of the application making changes to header files was pretty much impossible.

If some cases you just need to do a hack.

In the source file from which you need to access the private data member you can put in this as a first line:

#define private public
#define protected public

and access anything you want.

like image 146
Jeroen Dirks Avatar answered Oct 14 '22 09:10

Jeroen Dirks


I've just added an entry to my blog that shows how it can be done in a completely conforming way. Here is an example on how you use it for the following class

struct A {
private:
  int member;
};

Just declare a tag name and instantiate a robber like the following example shows (my post shows the implementation of the robber). You can then access that member using a member pointer

struct Amem { typedef int type; };
template class rob<Amem, &A::member>;

int main() {
  A a;
  a.*result<Amem>::ptr = 42; // Doh!
}

But actually, this doesn't show that c++'s access rules aren't reliable. The language rules are designed to protect against accidental mistakes - if you try to rob data of an object, the language by-design does not take long ways to prevent you.


The above is a way to access private and protected members in a conforming way. This one is another way to access protected members in a Standard conforming way. The basic idea is to use a member pointer

std::deque<int> &getAdapted(std::stack<int> &s) {
    struct voyeur : stack<int> 
    { using stack<int>::c; };
    return s.*(&voyeur::c);
}

int main() {
    std::stack<int> s;
    std::deque<int> &adapted = getAdapted(s);
    output(adapted); // print the stack...
}

No casting or type punning involved. It takes a pointer to a protected member of std::stack<int> through a class derived from it where that member name is public, so the compiler allows this. Then it uses it on a std::stack<int> object, which is allowed too.

like image 34
Johannes Schaub - litb Avatar answered Oct 14 '22 10:10

Johannes Schaub - litb