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.

80 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

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

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/

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

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

Comment poster said...

"I wish I had the words to describe how amazing this photo is. Simply stunning

Comment poster said...

This view is giving me major wanderlust. I need to plan a trip ASAP!"

Comment poster said...

"Digital marketing allows for personalized and tailored communication with customers."

Comment poster said...

Digital marketing is an ongoing process that requires constant monitoring and optimization."

Comment poster said...

This photo brings back memories of my own travels. It's incredible how images can evoke such emotions."

Comment poster said...

"Nature never ceases to amaze me. This photo captures its beauty perfectly."

Comment poster said...

"I am to describe how amazing this photo is. Simply stunning!"

Comment poster said...

This bedroom furniture set exudes elegance and sophistication. Its clean lines and luxurious materials create a serene and inviting atmosphere."

Comment poster said...

wish I could be there right now. This place looks like a dream!

Comment poster said...

"I love how the colors in this picture blend so beautifully. Mother Nature is an artist

Comment poster said...

Hats off to the team behind this outstanding website!"

Comment poster said...

Appreciating the user-centric approach and responsiveness."

Comment poster said...

20. "A big thank you to the creators for sharing their expertise with us!"

Comment poster said...

The Earth's well-being is intricately connected to our own well-being."

Comment poster said...

"Mother Nature deserves our utmost respect and protection."

Comment poster said...

Conservation efforts today will shape a greener world for generations to come."

Comment poster said...

"I'm in awe of the natural wonders our world has to offer. This photo is a true testament to that."

Comment poster said...

You have an eye for capturing beauty. Keep sharing these amazing photos with us!"

Comment poster said...

"You have an eye for capturing beauty. Keep sharing these amazing photos with us

Comment poster said...



"I've never seen anything like this before. Thanks for sharing this unique perspective!"

Comment poster said...

Wow, this picture is absolutely stunning

Comment poster said...

The world is full of hidden gems, and this photo just uncovered one. Absolutely mesmerizing!"

Comment poster said...

This photo reminds me why I love exploring and discovering new places. Thanks for the inspiration!"

Comment poster said...

Wow, this picture is absolutely stunning!

Comment poster said...

Nature never ceases to amaze me. This photo captures its beauty perfectly."

Comment poster said...

"I love how the colors in this picture blend so beautifully. Mother Nature is an artist!"

Comment poster said...

"I can almost hear the sound of waves crashing just by looking at this picture.

Comment poster said...

Bruhhhhhh you're excellent content writer"This place looks so peaceful and serene. I could spend hours just soaking in the beauty."

Comment poster said...

Bruhhhhhh you're excellent content writer

Comment poster said...

The world is full of incredible places, and this is definitely one of them. Thanks for sharing!"

Comment poster said...

"I can't get over how clear the water is in this picture. It's like paradise

Comment poster said...

Navigating the World of Decentralized Finance Safely and Seamlessly**

Comment poster said...

experienced cryptocurrency users.

Comment poster said...

In the rapidly expanding landscape of blockchain and cryptocurrency

Comment poster said...

and a web3 interface that allows users to interact with blockchain-based.

Comment poster said...

providing a user-friendly interface for both beginners and .

Comment poster said...

What sets Metamask apart is its focus on .

Comment poster said...

At its core, Metamask is a cryptocurrency wallet.

Comment poster said...

**Unveiling the New Twitter Logo X: A Bold Step into the Future**

Comment poster said...

experienced cryptocurrency users

Comment poster said...

applications using a browser extension or mobile app.

Comment poster said...

Whoa, talk about #travelgoals! Adding this to my bucket list for sure."

Comment poster said...

This place looks so peaceful and serene. I could spend hours just soaking in the beauty."

Comment poster said...

"I can't get over how clear the water is in this picture. It's like paradise!"

Comment poster said...

Bruhhhh!!! what A shit blog

Comment poster said...

I can't get over how clear the water is in this picture. It's like paradise!"

Mili Movers said...

I was facing the same problem with my company website Mili Movers but now going well after some changes

alfaa movers said...

Alfaa Movers in Dubai stands out as the premier choice for movers and packers in Business Bay, offering top-notch services tailored to clients' needs. With expertise in warehouse movers in Dubai, they ensure smooth transitions for businesses. Whether it's villa movers and packers or office relocation services in Dubai, Alfaa excels in providing efficient and hassle-free moves. Their dedication to quality, professionalism, and customer satisfaction makes them the go-to option for anyone seeking reliable moving and packing solutions in Dubai. Trust Alfaa Movers for a seamless experience from start to finish.