Saturday, July 3, 2010

Access to private members. That's easy!

So, always thought that it's impossible without undefined behavior to access private members of arbitrary classes without being friend.

Today I noticed I've been horribly wrong, after reading some insightful commit to the clang compiler, that enabled it to allow explicit instantiation to disregard accessibilities, as per the Standard. This enables us to access private members of others. As an experiment, I created some class templates

template<typename Tag>
struct result {
  /* export it ... */
  typedef typename Tag::type type;
  static type ptr;
};

template<typename Tag>
typename result<Tag>::type result<Tag>::ptr;

template<typename Tag, typename Tag::type p>
struct rob : result<Tag> {
  /* fill it ... */
  struct filler {
    filler() { result<Tag>::ptr = p; }
  };
  static filler filler_obj;
};

template<typename Tag, typename Tag::type p>
typename rob<Tag, p>::filler rob<Tag, p>::filler_obj;

So, how is it used? Let's have an example

struct A {
private:
  void f() {
    std::cout << "proof!" << std::endl;
  }
};

struct Af { typedef void(A::*type)(); };
template class rob<Af, &A::f>;

Ah, that's all to expose poor A's "f" member. Now anyone can use them using the member pointer snytax, as does the main function below

int main() {
  A a;
  (a.*result<Af>::ptr)();
}

Of course, as Herb Sutter told us, don't do these things in real code.

36 comments:

PTG said...

Cute hack :-)

Dolazy said...

I recently started to think whether enforcing privateness is really a good thing. It can be useful to have access to private variables if you are debugging with printf statements. Or when you are dealing with badly designed legacy code. If we can have a const_cast, then why not a "private_cast"?

Anonymous said...

Can you give the corresponding revision number of clang ?

Archiminos said...

I think you're forgetting that C++ is not an object-oriented language. It is a language that supports many object-oriented idioms.

I can think of several ways of accessing a private method in C++. Off the top of my head:

- Function Pointers
- Friend classes / functions.
- static member functions.
- copy constructors / assignment operators (allow access to private members of rhs if it's the same type).
- Just make it public(!)

I always view privacy as something to help other programmers. If something is private, I'm saying to any other programmer 'please don't interfere with this stuff when using this class'.

Of course they can still change it if they want to, but they have to consciously make that decision which means they will more likely be aware of the consequences of doing so.

shoe said...

i like to use #define private public and #define protected public

Johannes (litb) said...

Guys, Herb Sutter says "This isn't actually a problem. The issue here is of protecting against Murphy vs. protecting against Machiavelli... that is, protecting against accidental misuse (which the language does very well) vs. protecting against deliberate abuse (which is effectively impossible). In the end, if a programmer wants badly enough to subvert the system, he'll find a way, as demonstrated above in Examples 1 to 3.". You do *not* want to do this at home. You also do want to notice: This blog demonstrates a way that your compiler will have to support in order to be a C++ compiler. Any #define hacks and the-like are not guaranteed to work.

Jesse said...

Wow. Any chance of posting a follow-up to explain a little more what is going on? Does the function pointer declaration typedef void(A::*type)() need to match the private method you are trying to access?

jcmvbkbc said...

Applying this method to virtual functions one may only call final overriding method of the object's type, ancestor methods are not accessible.

E.g.:

struct A {
private:
virtual void f() {
std::cout << "proof!" << std::endl;
}
};

struct B: public A {
private:
virtual void f() {
std::cout << "not proof!" << std::endl;
}
};

struct Af { typedef void(A::*type)(); };
template class rob;

int main() {
B a;
(a.*result::ptr)();
}

would print "not proof!" (B::f), although we'd like to see "proof!" (A::f).

Anonymous said...

sorry, but I got a compile error
VS 2008
: error C2248: 'A::f' : cannot access private member declared in class 'A'

Dave Abrahams said...

Spending some time cleaning this up and simplifying it... it looks like derivation of rob from result is superfluous.

Dave Abrahams said...

Having analyzed and rewritten the code it turns out I ended up very close to where you started! Here's my version including explanatory comments: https://gist.github.com/1528856

Anonymous said...

very nice. but it won't work if A::f() is overloaded.

Anonymous said...

well, I have to swallow my own words -- it actually works even with overloaded functions, if you use the RIGHT compiler :) GCC handles it well, whereas MSVC complains about not being able to access private member...

Anonymous said...

Thank you for the solution! private QCheckListItem::setState(int,bool,bool) in Qt3 has the complexity > O^2 when the checkbox parent is the checkbox controller when legally called

Unknown said...

Nice ...

And ideas how this could be extended to also access private _static_ members?

Unknown said...

Found out how to do it with static members myself:

struct A {
private:
static void f() {
std::cout << "proof!" << std::endl;
}
};

struct Af { typedef void(*type)(); };
template class rob;

int main() {
A a;
(*result::ptr)();
}

Anonymous said...

I get segfaults with gcc and clang (https://wandbox.org/permlink/CWeIkBwi95eSpLPK). Clang spits out a couple of warnings in addition.
Am I missing something how to get this working?

Luiz said...

Yes, in real code we just cast to void* and access the VTable index manually. It's also easier to understand what's happening.

Self Storage in Dubai said...

This is what I get on that page, Nice Post and Appreciated your support. Thank you so much for sharing such a detailed information. We are proud that clients hold against using our moving company.
movers and packers
movers

Mr Dubai Movers and Packers said...

We are very very thankful two you being support us very good content and i get good knowledge

Movers and Packers in Dubai 

Movers and Packers in Sharjah

Movers and Packers in Dubai 

Movers and Packers in Sharjah

Professional Movers and Packers in Dubai Sharjah said...

Experts blog writer I like it and same as one of our blog like Movers and Packers in Dubai
Movers and Packers in Sharjah
Movers and Packers in Dubai
Movers and Packers in Sharjah
House Movers and Packers in Dubai
Movers and Packers in Dubai
Movers and Packers in Sharjah

Movers Packers Dubai Sharjah Ajman said...

Thanks you
100% Guaranteed Services
We can provide the Fast and reliable 100% Guaranteed Services within the agreement. Our work will be satisfied to you.Movers and Packers in Dubai Movers and Packers in DubaiMovers and Packers in Dubai

Movers and Packers in Dubai Best Movers said...

I Really Really Thanks to you Experts blog writer I like it and same as one of our blog like Movers and Packers in Dubai

Movers and Packers in Dubai

House Movers and Packers in Dubai
Movers and Packers in Dubai

Dubai Movers and Packers Best Moving Company LLC said...

Great...!I Really Really Thanks to you Experts blog writer I like it and same as one of our blog like
Movers and Packers in Dubai

Movers and Packers in Dubai said...

Movers and packers in Dubai our expert movers and packers in Dubai are in a function to p. C. Pass any form of gadgets from any type of services within the metropolis with modern-day generation. Ali movers with its greatly accelerated community of relocation cars, storehouses hard work workplace now offers the subsequent offerings in dubai. Movers and packers in dubai are you looking for a expert shifting shifting agency. A transferring business enterprise that may offer low priced, reliable and moreover nicely timed packing and moving offerings inside the uae.Thanks to you Experts blog writer I like it and same as one of our blog like Movers and Packers in Dubai

Movers and Packers in Dubai

House Moving Companies in Dubai
http://moverspackers-dubai.com/2019/01/26/movers-and-packers-in-dubai

Best House Movers and Packers in Dubai said...

Best House Movers and packers in dubai are you looking for a expert shifting shifting agency. A transferring business enterprise that may offer low priced, reliable and moreover nicely timed packing and moving offerings inside the uae.Thanks to you Experts blog writer I like it and same as one of our blog like Movers and Packers in Dubai

Movers and Packers in Dubai

House Moving Companies in Dubai
http://moverspackers-dubai.com/2019/01/26/movers-and-packers-in-dubai

Dubai Sharjah Moving Company said...

We provides you to Very Fast and Efficient service
we are doing the work given a specific time. Movers and Packers in Dubai

Movers and Packers in Dubaihttp://moverspackers-dubai.com/2019/01/26/movers-and-packers-in-dubai/

House Moving Company in Dubai
http://moverspackers-dubai.com/2018/12/04/house-movers-and-packers-in-dubai/

Al Fajer Movers and Packers in Dubai said...

as a Head office with branches network in Dubai Sharjah Abu dhabi Ajman Al ain. We have skilled team /staff of Packers /Managers to assist for all your packing and moving needs, Customs clearing agent, Freight Forwarding Service, Goods transportation, House shifting and relocation, Cargo services Movers and Packers in Dubai

Movers and Packers in Dubaihttps://moversandpackersdubai.com/category/movers-and-packers-in-dubai/

House Moving Company in Dubai
https://moversandpackersdubai.com/category/house-movers-and-packers-in-dubai/

Moversandpackers said...

service basket uae
movers and packers in dubai

Movers and Packers in Dubai said...

Movers and Packers in Dubai
Movers and Packers in Sharjah
Movers and Packers in Dubai

DXB Movers and Packers UAE said...

DXB Movers and Packers UAE
Movers and Packers in Dubai

Movers and Packers Dubai

Movers And Packers In Dubai Get on Cheap Price Shifting Moving said...

Dear Vistors Actully This Is the Link About House Office And Villa, Apartment Studio household Stuff Moving Shifting One Place To Other So Totaly You Understod If You Are Intrested Than Click On The Link And Go On Our Wbe Site Professional Sh Movers Than Read More About Us This Link About Movers And packers In Dubai ServicesProfessional Movers And Packers In Dubai

travel now said...

I am so gleeful when i found your weblog while I was researching on Bing for something else,but believe me the way you interact is literally awesome I do respect that so much. I will instantly get your rss and stay informed of any updates you make and as well take the advantage to share some vital information regarding. how to legally live in cyprus I will also take the advantage to ask for your permission to join our TELEGRAM GROUP

Movers Company said...

Beautiful blog post. Please follow our site links
https://Dubaimoverscompany.com/
Https://trendmoversdubai.com/
WWW.TRENDMOVERSDUBAI.COM

Best Local Movers in Dubai said...

Saba movers are the leading cargo movers in Dubai that provide a wide range of cargo moving services to its clients at competitive prices

Expert Movers and Packers Dubai said...

https://goo.gl/maps/KzcWZp17FQv8iYS2A