Access private member of C ++ parent class

I have a basic question in C ++, which unfortunately puzzles me. I recently came across an article that uses down-casting to access a private member of a class using down-casting. My question is, why does it work?

Given that I have a parent class P with a private member m_p of type dummy *, then the method used was to create the hack hackP class as follows:

class hackP: public P { public: dummy *m_p; }; 

which apparently gets access to class P to the private member m_p with a code snippet like

 P parent = ...; hackP *hp = (hackP*)&parent; // access parent m_p as hp->m_p 

Any help would be appreciated.

+4
source share
1 answer

GotW #76 The use and abuse of accessibility seems to cover this topic pretty well, and I have to say that I took some interesting bits that I did not know from it.

This article Accesses private members. It is easy! It takes a little more effort to wrap your head, but seems more flexible.

This answer from this topic Is a private member hacked in a certain way? , which is very similar, but not identical, it seems that this behavior is undefined, since the layout will not be guaranteed to match between access-qualifier sections. From the draft C ++ standard , section 9.2 class members say (focus):

Non-static data members of a (non-unitary) class with the same access (Section 11) are allocated so that later members have higher addresses inside the class object. The distribution order of non-static data members with different access control is not defined (11).

+5
source

Source: https://habr.com/ru/post/1483202/


All Articles