Note that there are some explanatory texts on larger screens.

plurals
  1. POSubclass casting, and pointer address changes
    text
    copied!<p>I've been using multiple inheritance in c++ for quite a long time, but only realised today that this could imply that the pointer addresses could be different when referencing them as one of the subclasses.</p> <p>For example, if I have:</p> <pre><code> class ClassA{ public: int x; int y; ClassA(){ cout &lt;&lt; "ClassA : " &lt;&lt; (unsigned int)this &lt;&lt; endl; } }; class ClassC{ public: int cc; int xx; ClassC(){ cout &lt;&lt; "ClassC : " &lt;&lt; (unsigned int)this &lt;&lt; endl; } }; class ClassB : public ClassC, public ClassA{ public: int z; int v; ClassB(){ cout &lt;&lt; "ClassB : " &lt;&lt; (unsigned int)this &lt;&lt; endl; } }; int main(){ ClassB * b = new ClassB(); } </code></pre> <p>class A and class C have different addresses when printed on the constructor.</p> <p>Yet, when I try to cast them back to each other, it just works automagically:</p> <pre><code>ClassA * the_a = (ClassA*)b; cout &lt;&lt; "The A, casted : " &lt;&lt; (unsigned int)the_a &lt;&lt; endl; ClassB * the_b = (ClassB*)the_a; cout &lt;&lt; "The B, casted back : " &lt;&lt; (unsigned int)the_b &lt;&lt; endl; </code></pre> <p>I suppose this kind of information can be derived by the compiler from the code, but is it safe to assume that this works on all compilers?</p> <p><strong>Additional Question</strong> : is it possible to force the order in which the subclass locations go? For example, if I need classA to be located first (essentially, share the same pointer location) as ClassC which subclasses it, do I just need to put it first in the declaration of subclasses? <strong>Update</strong> Okay, looks like it's not possible to force the order. Is it still possible to find out the "root" address of the structure, the start of the address allocated to the subclass, at the superclass level? For example, getting classB's address from ClassA.</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