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?
Let's make a few minor changes to your code:
In the above call, there is no way of knowing which sub-type of
B
bp
points to. It could beC
,D
, or something else. If you step into the call you would know which sub-type ofB
bp
points to.