如果派生类除了继承自父类的虚函数之外没有其他虚函数,那么是否会为该派生类创建虚表?
例如:
class A{
public:
virtual void show();
};
class B : public A
{
};
类B的虚拟表如何?
如果派生类除了继承自父类的虚函数之外没有其他虚函数,那么是否会为该派生类创建虚表?
例如:
class A{
public:
virtual void show();
};
class B : public A
{
};
当使用g++编译器(Ubuntu 8.2.0-1ubuntu2~18.04)8.2.0版本时,以下是gdb的原始回答:
15 class A
16 {
17 public:
18 virtual void show(){}
19 };
20
21 class B:public A
22 {
23 };
24
(gdb) l
25 int main()
26 {
27 A a;
28 B b;
29 }
(gdb) p a
$5 = {_vptr.A = 0x55555575f5c8 <vtable for A+16>}
(gdb) p b
$6 = {<A> = {_vptr.A = 0x55555575f5b0 <vtable for B+16>}, <No data fields>}
(gdb)
您可以通过查看对象的内容来检查它。我编写了这个简单的程序,打印出基类、派生类和一个与基类相同但具有普通方法而不是虚拟方法的类的内容:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Base {
public:
virtual void show() {}
};
class Derived : public Base
{ };
class NonVirtual {
public:
void show() {}
};
struct Test
{
int data1, data2;
};
template <typename T>
void showContents(T* obj, string name)
{
Test* test = new Test{};
test = reinterpret_cast<Test*>(obj);
cout << name << ": " << hex << "0x" << test->data1 << " " << "0x" << test->data2 << endl;
delete test;
}
int main()
{
Base* base = new Base{};
Derived* derived = new Derived{};
NonVirtual* nonVirtual = new NonVirtual{};
showContents(base, "Base");
showContents(derived, "Derived");
showContents(nonVirtual, "NonVirtual");
delete base;
delete derived;
delete nonVirtual;
}
Base: 0x4013e0 0x0
Derived: 0x401400 0x0
NonVirtual: 0x0 0x0
所以我期望它意味着确实为Derived
对象创建了一个虚拟表(至少对于这个编译器而言——因为在C++标准中未定义所需的行为)。