Note that there are some explanatory texts on larger screens.

plurals
  1. POC++: is a class with virtual base but without virtual functions polymorphic and has VTable?
    text
    copied!<p>Consider the following code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;typeinfo&gt; #include &lt;type_traits&gt; 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 &lt;&lt; sizeof(B1) &lt;&lt; endl; cout &lt;&lt; sizeof(B2) &lt;&lt; endl; cout &lt;&lt; sizeof(Derived) &lt;&lt; endl; cout &lt;&lt; std::is_polymorphic&lt;B1&gt;::value &lt;&lt; endl; cout &lt;&lt; std::is_polymorphic&lt;B2&gt;::value &lt;&lt; endl; cout &lt;&lt; std::is_polymorphic&lt;Derived&gt;::value &lt;&lt; endl; return 0; } </code></pre> <p>On my system it prints</p> <pre><code>4 8 12 0 0 0 </code></pre> <p>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 <code>-fdump-class-hierarchy</code> and got:</p> <pre><code>Vtable for B2 B2::_ZTV2B2: 3u entries 0 4u 4 (int (*)(...))0 8 (int (*)(...))(&amp; _ZTI2B2) VTT for B2 B2::_ZTT2B2: 1u entries 0 ((&amp; B2::_ZTV2B2) + 12u) Class B2 size=8 align=4 base size=4 base align=4 B2 (0x0x3ca5400) 0 nearly-empty vptridx=0u vptr=((&amp; B2::_ZTV2B2) + 12u) A (0x0x3c972d8) 4 virtual vbaseoffset=-12 </code></pre> <p>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?</p> <p>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 <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n1529.html#1.2.4.1" rel="noreferrer">this</a> 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.)".</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload