1

I used a third-part library in my company. In it, Some classes I need is defined like this:

class A
{};

class B : public A
{};

class C : public A
{};

class Foo
 : public B
 , public C
 , public A
{};

And here, I need to gain offsets between Foo and all it's base classes. so I code like this:

int main()
{

    Foo* f = new Foo();

    int_ptr ptrb = ((B*)(Foo*)0x1) - 0x1;
    int_ptr ptrc = ((C*)(Foo*)0x1) - 0x1;

    int_ptr ptra = ((A*)(Foo*)0x1) - 0x1;     // error
    A *ptr = (A*)(Foo*)f;     // error

    cout << "Hello world!" << endl;
    return 0;
}

in VC2010 and VC2012, it's all okay.

but in GCC 4.7.3, there will be a "Ambiguous base" compile-error.

I may not modify any code of the declaration. How could I gain the offset between Foo and the last "public A" ?

curiousguy
  • 8,038
  • 2
  • 40
  • 58
  • 1
    Is a Foo object really supposed to contain 3 instances of A? In many cases, what’s really needed is 1 shared instance, so you’d use a virtual base class. – microtherion May 10 '13 at 00:41
  • If you want the offset to then invoke a method, why not invoke the method directly? – MattD May 10 '13 at 01:27
  • Thanks for your replies. In fact, in my project, we used a 3rd-part library. In the library there are some COM-interfaces and some classes implement them. If there is a class implement some interfaces, I need to show distance from each interface to it's class. But unfortunately I cannot modify any code of that library. – noslopforever May 10 '13 at 05:06
  • retag: this is an inherently ambiguous inheritance, so removing compiler-specific tag – curiousguy May 14 '13 at 05:37

1 Answers1

0

Your code can be simplified:

class A
{};

class B : public A
{};

class Foo
 : public B
 , public A
{};

Here the Foo class has two A base classes

  • one indirect base class A named Foo::B::A
  • a direct base class A that you cannot name in C++

You will be able get the B::A base class subobject of a Foo object:

Foo f;
B &b = f;
A &a = b;

but not the other A impossible-to-name base class subobject.

You created an ambiguous inheritance situation.

Conclusion: do not do that.

Also: I really have no idea what you were really trying to do.

curiousguy
  • 8,038
  • 2
  • 40
  • 58