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?

1

There are 1 answers

2
R Sahu On BEST ANSWER

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);
}