Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This works:</p> <pre><code>#include &lt;iostream&gt; using namespace std; class test { public: int a; int b; test () : c(100) {} void show () {cout &lt;&lt; "c = " &lt;&lt; c &lt;&lt; endl;} private: int c; }; int main (void) { test x; test *ptr; ptr = &amp;x; ptr++; ptr = (test *) ((int *)ptr - 1); cout &lt;&lt; "c = " &lt;&lt; *((int *)ptr) &lt;&lt; endl; *((int *)ptr) = 200; x.show (); return 0; } </code></pre> <p>But the offset should be known. In the above <code>ptr</code> is type of <code>test</code> and therefore <code>ptr++</code> will increment the pointer value to <code>sizeof (test)</code>. Because the location of the private member <code>c</code> is at the end and is a type of integer so one integer step is decreased by casting <code>ptr</code> into <code>int *</code> first and then decrementing 1, which now points to the address of <code>c</code>. It is printed first, and next the value of <code>c</code> is modified by first casting <code>ptr</code> to <code>int *</code> and then assigning a value, and then printed.</p> <p>It is not guaranteed that it will always get the value of <code>c</code> when you know the position of <code>c</code> as the padding might be different in other cases. Also there is no point accessing a private data member because at the time of the object design approach it was made to be accessed by the member functions and is a tool for organization by providing abstraction. When implementing such a concept in other languages like C, which does not have object oriented features, you can implement such a private - public environment by personally following a convention, but the compiler will not enforce anything if you accessed a "private" where you actually shouldn't. But in C++ the compiler provides the restriction and stops you from diverting and breaking the object orientated design which you made. At run time all's in memory and you can access them without any restriction from your code at that time nothings private or public. If you know how to interpret the bytes in the executable you can change anything you like, even the code itself. I do not think this is a good idea to be implemented, as it will make the code unpredictable and unportable and definitely violate the OOD approach.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload