Consider the following code:
#include <iostream>
#include <typeinfo>
#include <type_traits>
using namespace std;
struct A { int data; };
struct B1 : A {};
struct B2 : virtual A {};
struct Base1 : virtual A {};
struct Base2 : virtual A {};
struct Derived : Base1, Base2 {};
int main() {
cout << sizeof(B1) << endl;
cout << sizeof(B2) << endl;
cout << sizeof(Derived) << endl;
cout << std::is_polymorphic<B1>::value << endl;
cout << std::is_polymorphic<B2>::value << endl;
cout << std::is_polymorphic<Derived>::value << endl;
return 0;
}
On my system it prints
4
8
12
0
0
0
Which means that none of these classes is polymorphic. However, sizes of B1 and B2 differ by exactly size of a pointer, which is probably a pointer to vtable. I've ran gcc with -fdump-class-hierarchy
and got:
Vtable for B2
B2::_ZTV2B2: 3u entries
0 4u
4 (int (*)(...))0
8 (int (*)(...))(& _ZTI2B2)
VTT for B2
B2::_ZTT2B2: 1u entries
0 ((& B2::_ZTV2B2) + 12u)
Class B2
size=8 align=4
base size=4 base align=4
B2 (0x0x3ca5400) 0 nearly-empty
vptridx=0u vptr=((& B2::_ZTV2B2) + 12u)
A (0x0x3c972d8) 4 virtual
vbaseoffset=-12
Here is a question: what is a polymorphic class? Does 'having vtable' means 'be polymorphic and have RTTI' and vice-versa? If not, why do it have to have at least one virtual function to be polymorphic, if it's going to have vtable anyway?
Looks like definition of polymorphic class differs from 'the class that has a vtable', because, as we can see above, B2 is not a polymorphic, but has a vtable and, as I think, should have a RTTI. In this document it's clearly stated that "polymorphic - i.e. have at least one virtual function. (This is necessary to allow the generated dispatch code to use RTTI on the classes.)".