Subclass Change and Pointer Address Change

I have been using multiple inheritance in C ++ for quite some time, but I realized only today that this could mean that the addresses of pointers may differ when they are mentioned as one of the subclasses.

For example, if I have:

  class ClassA{
     public:
        int x;
        int y;
        ClassA(){
           cout << "ClassA : " << (unsigned int)this << endl;
        }
  };

  class ClassC{
     public:
        int cc;
        int xx;
        ClassC(){
           cout << "ClassC : " << (unsigned int)this << endl;
        }
  };

  class ClassB : public ClassC, public ClassA{
     public:
        int z;
        int v;
        ClassB(){
           cout << "ClassB : " << (unsigned int)this << endl;
        }
  };


  int main(){

     ClassB * b = new ClassB();

  }

class A and class C have different addresses when printed in the constructor.

However, when I try to drop them to each other, it just works automatically:

ClassA * the_a = (ClassA*)b;
cout << "The A, casted : " << (unsigned int)the_a << endl;

ClassB * the_b = (ClassB*)the_a;
cout << "The B, casted back : " << (unsigned int)the_b << endl;

I believe that such information can be obtained by the compiler from the code, but can it be assumed that this works on all compilers?

: ? , , classA ( , ) ClassC, , ? , , . "" , , , ? , B ClassA.

+5
3

, . , , "C" static_cast .

.

: - , .

+6

, , . ++ base-to- .

, , . , :

ClassB* b = new ClassB;
ClassC* c = (ClassC*)(void*)b;

, C void *, , B, .

, . , , dynamic_cast, , .

+3

, .

, . ( Microsoft, ) . ( ), , , , - .

- . A B A, B ( , X, ). , : ( A, B).

What is even more hairy is that the presented structure is obliged "according to the law of the Standard" to dynamically change during construction and destruction, so the construction and destruction of complex objects is slow. However, when they are done, method calls, even cross-calls, are pretty fast.

+1
source

All Articles