C++: is a class with virtual base but without virtual functions polymorphic and has VTable?

两盒软妹~` 提交于 2019-12-05 05:55:47

You are missing a detail here: virtual tables are an implementation detail. As a result:

  • the Standard defines polymorphic classes as classes that can be used in a polymorphic sense: ie, where behavior can be overriden
  • compilers use virtual tables to implement some features/behaviors mandated by the Standard, which happen to include both polymorphic classes AND virtual bases.

Thus, yes the compilers I know (MSVC and those following the Itanium ABI such as gcc, icc and Clang) will use virtual tables to provide the RTTI necessary for dynamic_cast to work in the presence of virtual bases... and no this has nothing to do really with whether a class is polymorphic or not.

On a tangent, though, Prefer Composition Over Inheritance implies that there is little reason to inherit from a class if there is no behavior that can be overriden.

Here is a defenition of std::is_polymorphic

If T is a polymorphic class (that is, a class that declares or inherits at least one virtual function), provides the member constant value equal true. For any other type, value is false.

Since no functions are defined virtual, it will return false.

To elaborate, we should distinguish between polymorphism and vtables. In C++ vtables are indeed needed for polymorphism, but also for other non-polymorphic concepts too.

I could try to explain virtual inheritance, which when used with multiple inheritance will create a vtable, but this link does it better.

For those curious about the effects of the VTable provided by the inheritance.

The following sample

struct VB{
   // virtual int f(){}
};

struct IA:virtual VB{};

int main(int argc, char** argv) {
    VB* o = new IA;

    IA* iap = dynamic_cast<IA*>(o);

}

will not compile (g++ 4.8):

main.cpp: In function ‘int main(int, char**)’: main.cpp:26:34: error: cannot dynamic_cast ‘o’ (of type ‘struct VB*’) to type ‘struct IA*’ (source type is not polymorphic) IA* iap = dynamic_cast(o);

While uncommenting the int f() member gives the desired result.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!