(C ++、MinGW 4.4.0、Windows OS)
ラベル<1>と<2>を除いて、コードでコメントされているのは私の推測です。私がどこか間違っていると思われる場合に備えて、私を訂正してください。
class A {
public:
virtual void disp(); //not necessary to define as placeholder in vtable entry will be
//overwritten when derived class's vtable entry is prepared after
//invoking Base ctor (unless we do new A instead of new B in main() below)
};
class B :public A {
public:
B() : x(100) {}
void disp() {std::printf("%d",x);}
int x;
};
int main() {
A* aptr=new B; //memory model and vtable of B (say vtbl_B) is assigned to aptr
aptr->disp(); //<1> no error
std::printf("%d",aptr->x); //<2> error -> A knows nothing about x
}
<2>はエラーであり、明らかです。なぜ<1>はエラーではないのですか?この呼び出しで起こっていると思うのはaptr->disp(); --> (*aptr->*(vtbl_B + offset to disp))(aptr)
aptr
、パラメーターがメンバー関数への暗黙のthis
ポインターであるということです。内部disp()
にあるstd::printf("%d",x); --> std::printf("%d",aptr->x); SAME AS std::printf("%d",this->x);
ので、なぜ<1>はエラーを出さないのに<2>はエラーを出さないのですか?
(vtablesは実装固有のものであることは知っていますが、それでも質問する価値があると思います)