Virtual Method Table - Example

Example

Consider the following class declarations in C++ syntax:

class B1 { public: void f0 {} virtual void f1 {} int int_in_b1; }; class B2 { public: virtual void f2 {} int int_in_b2; };

used to derive the following class:

class D : public B1, public B2 { public: void d {} void f2 {} // override B2::f2 int int_in_d; };

and the following piece of C++ code:

B2 *b2 = new B2; D *d = new D;

g++ 3.4.6 from GCC produces the following 32-bit memory layout for the object b2:

b2: +0: pointer to virtual method table of B2 +4: value of int_in_b2 virtual method table of B2: +0: B2::f2

and the following memory layout for the object d:

d: +0: pointer to virtual method table of D (for B1) +4: value of int_in_b1 +8: pointer to virtual method table of D (for B2) +12: value of int_in_b2 +16: value of int_in_d Total size: 20 Bytes. virtual method table of D (for B1): +0: B1::f1 // B1::f1 is not overridden virtual method table of D (for B2): +8: D::f2 // B2::f2 is overridden by D::f2

Note that those functions not carrying the keyword virtual in their declaration (such as f0 and d) do not generally appear in the vtable. There are exceptions for special cases as posed by the default constructor.

Overriding of the method f2 in class D is implemented by duplicating the virtual method table of B2 and replacing the pointer to B2::f2 with a pointer to D::f2.

Read more about this topic:  Virtual Method Table

Famous quotes containing the word example:

    Our intellect is not the most subtle, the most powerful, the most appropriate, instrument for revealing the truth. It is life that, little by little, example by example, permits us to see that what is most important to our heart, or to our mind, is learned not by reasoning but through other agencies. Then it is that the intellect, observing their superiority, abdicates its control to them upon reasoned grounds and agrees to become their collaborator and lackey.
    Marcel Proust (1871–1922)