除了父类是虚函数之外没有任何虚函数的派生类的虚表

Ano*_*mar 5 c++ polymorphism inheritance

是否将为派生类创建虚拟表,除了父类之外没有任何虚函数,虚拟函数不会被派生类覆盖.

对于前:

class A{
public:
    virtual void show();

};

class B : public A
{

};
Run Code Online (Sandbox Code Playgroud)

B类虚拟表怎么样?

Pio*_*iwa 0

您可以通过查看对象的内容来检查它。我编写了这个简单的程序,它打印基类、派生类和与基类相同但使用普通方法而不是虚拟方法的类的内容:

#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;
}
Run Code Online (Sandbox Code Playgroud)

现场演示


使用cpp.sh编译上述程序后运行的结果(我不确定那里使用的是什么编译器):

Base: 0x4013e0 0x0
Derived: 0x401400 0x0
NonVirtual: 0x0 0x0
Run Code Online (Sandbox Code Playgroud)

所以我希望它意味着确实为该对象创建了一个虚拟表Derived(至少对于这个编译器来说 - 因为 C++ 标准中没有定义所需的行为)。