Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can imagine this code:</p> <pre><code>struct A { void f() {} int int_in_b1; }; int main() { A a; a.f(); return 0; } </code></pre> <p>Being transformed into something like:</p> <pre><code>struct A { int int_in_b1; }; void A__f(A* const this) {} int main() { A a; A__f(&amp;a); return 0; } </code></pre> <p>Calling <em>f</em> is straight-forward because it's non-virtual. (And sometimes for virtual calls, the virtual dispatch can be avoided if the dynamic type of the object is known, as it is here.)</p> <hr> <p>A longer example that will either give you an idea about how virtual functions work or terribly confuse you:</p> <pre><code>struct B { virtual void foo() { puts(__func__); } }; struct D : B { virtual void foo() { puts(__func__); } }; int main() { B* a[] = { new B(), new D() }; a[0]-&gt;foo(); a[1]-&gt;foo(); return 0; } </code></pre> <p>Becomes something like:</p> <pre><code>void B_foo(void) { puts(__func__); } void D_foo(void) { puts(__func__); } struct B_VT { void (*foo)(void); } B_vtable = { B_foo }, D_vtable = { D_foo }; typedef struct B { struct B_VT* vt; } B; B* new_B(void) { B* p = malloc(sizeof(B)); p-&gt;vt = &amp;B_vtable; return p; } typedef struct D { struct B_VT* vt; } D; D* new_D(void) { D* p = malloc(sizeof(D)); p-&gt;vt = &amp;D_vtable; return p; } int main() { B* a[] = {new_B(), new_D()}; a[0]-&gt;vt-&gt;foo(); a[1]-&gt;vt-&gt;foo(); return 0; } </code></pre> <p>Each object only has one vtable pointer, and you can add many virtual methods to the class without affecting object size. (The vtable grows, but this is stored once per class and is not significant size overhead.) Note that I've simplified many details in this example, but it <a href="http://codepad.org/zDkd4LZD" rel="noreferrer">does work</a>: destructors are not addressed (which should additionally be virtual here), it leaks memory, and the <em>__func__</em> values will be slightly different (they're generated by the compiler for the current function's name), among others.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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