Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

c++ - Subclass casting, and pointer address changes

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.

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 on the constructor.

Yet, when I try to cast them back to each other, it just works automagically:

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 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?

Additional Question : 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? Update 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That's a perfectly standard use of multiple inheritance, and it will work on any compliant compiler. You should however note that an explicit cast in unnecessary in the first case, and that the 'C style cast' could be replaced by a static_cast in the second.

Is it possible to force the order in which the subclass locations go.

No : the layout is implementation defined, and your code should not depend on this ordering.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...