1

Example 3:(page 377)

class A {virtual void f();};
class B {virtual void f(); virtual void g();};
class C: A, B {void f();};
A* pa = new C;
B* pb = new C;
C* pc = new C;
pa->f();
pb->f();
pc->f();
pc->g()

(1) In Multiple inheritance for C++, Bjarne wrote: On entry to C::f, the this pointer must point to the beginning of the C object (and not to the B part). However, it is not in general known at compile time that the B pointed to by pb is part of a C so the compiler cannot subtract the constant delta(B).

Why does the compiler not know that B pointed to by pb is part of a C at compile time? Based on my understanding, B pointed to by pb is definitely a part of C since we new C and C inherits from B!

What about B* pb = new B;? does the compile know B pointed to by pb is a standlone object?

Fihop
  • 3,127
  • 9
  • 42
  • 65

1 Answers1

2

Let's make a few minor changes to your code:

struct A {virtual void f() {}};
struct B {virtual void f() {} virtual void g() {}};

void foo(B* bp)
{
   bp->f();
}

In the above call, there is no way of knowing which sub-type of B bp points to. It could be C, D, or something else. If you step into the call you would know which sub-type of B bp points to.

struct C : A, B {void f() {}};
struct D : B {void f() {}};

int main()
{
   B* pb1 = new C;
   B* pb2 = new D;

   foo(pb1);
   foo(pb2);
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • So when passing `pb1` or `pb2` to the function `foo`, the compiler only knows, ooh, okay, that's a `B` pointer, nothing else! Am I right? – Fihop Jun 10 '15 at 21:13
  • Sahu, I have another question, can you help me have look at it? http://stackoverflow.com/questions/30766982/virtual-method-table-for-multiple-inheritance – Fihop Jun 10 '15 at 22:25