37. class A {
public:
virtual void foo();
virtual void bar();
};
class B : public A {
public:
virtual void foo();
};
A's vtable
B's vtable
A::foo
A::bar
B::foo
A::bar
38. class A {
public:
virtual void foo();
virtual void bar();
};
class B : public A {
public:
virtual void foo();
};
A's vtable
B's vtable
A::foo
A::bar
B::foo
A::bar
B instance
vptr
p1
A* p1 = new B();
39. class A {
public:
virtual void foo();
virtual void bar();
};
class B : public A {
public:
virtual void foo();
};
A's vtable
B's vtable
A::foo
A::bar
B::foo
A::bar
B instance
vptr
A instance
vptr
p1
p2
A* p1 = new B();
A* p2 = new A();
40. class A {
public:
virtual void foo();
virtual void bar();
};
class B : public A {
public:
virtual void foo();
};
A's vtable
B's vtable
A::foo
A::bar
B::foo
A::bar
B instance
vptr
A instance
Aのポインタ経由でも
vptr
正しくBのメソッドを呼べる
p1
p2
A* p1 = new B();
A* p2 = new A();
41. 仮想関数テーブル実物
class Base
{
public:
virtual ~Base() {}
virtual int foo() = 0;
virtual int bar() {return 42;}
};
0 (int (*)(...))0
8 (int (*)(...))(& _ZTI4Base)
16 (int (*)(...))Base::~Base
24 (int (*)(...))Base::~Base
32 (int (*)(...))__cxa_pure_virtual
40 (int (*)(...))Base::bar
class MyClass : public Base
{
public:
virtual int foo() {return 43;}
};
0
8
16
24
32
40
(int (*)(...))0
(int (*)(...))(& _ZTI7MyClass)
(int (*)(...))MyClass::~MyClass
(int (*)(...))MyClass::~MyClass
(int (*)(...))MyClass::foo
(int (*)(...))Base::bar
42. 仮想関数テーブル実物
class Base
{
public:
virtual ~Base() {}
virtual int foo() = 0;
virtual int bar() {return 42;}
};
0 (int (*)(...))0
8 (int (*)(...))(& _ZTI4Base)
16 (int (*)(...))Base::~Base
24 (int (*)(...))Base::~Base
32 (int (*)(...))__cxa_pure_virtual
40 (int (*)(...))Base::bar
自分で実装
class MyClass : public Base
{
public:
virtual int foo() {return 43;}
};
0
8
16
24
32
40
(int (*)(...))0
(int (*)(...))(& _ZTI7MyClass)
(int (*)(...))MyClass::~MyClass
(int (*)(...))MyClass::~MyClass
(int (*)(...))MyClass::foo
(int (*)(...))Base::bar