虚函数相关的题目笔记
#include <iostream> class A { public: virtual void fun() { std::cout << "A" << std::endl; } int i; }; class B : public A { public: virtual void fun() { std::cout << "B" << std::endl; } int j; }; class C : public A { public: virtual void fun() { std::cout << "C" << std::endl; } virtual void fun2() { std::cout << "C2" << std::endl; } int k; }; int main() { A a; B b; C c; return 0; }
上面的例子主要是想知道B,C是否会有自己的虚表指针,结果我用gdb -g test.cpp进行调试,发现:
p a -> {_vptr.A = 0x400c28 <vtable for A+16>, i = 4197277}
p b -> {<A> = {_vptr.A = 0x400c10 <vtable for B+16>, i = 0}, j = 0}
p c -> {<A> = {_vptr.A = 0x400bf0 <vtable for C+16>, i = 4196496}, k = 0}
a,b,c都是只有一个虚表指针,并且指向的是不同的虚表。