Details about VPTR, Virtual table, Virtual Function

Home Forums C Programming Details about VPTR, Virtual table, Virtual Function

This topic contains 1 reply, has 2 voices, and was last updated by  bharat123 9 years, 9 months ago.

  • Author
    Posts
  • #2061

    shalizy
    Member

    Assumption: machine is 32-bit .
    Here I am going to explain How Virtual table, Virtual pointer for Virtual functions are internally working.
    First we have understand memory layout.
    Example 1: How the class’s memory layout

    Output:
    Sobj’s Size = 8
    obj ‘s Address = 0012FF7C
    Note: Any Plane member function does not take any memory.

    Example 2: Memory Layout of Derived class

    OUTPUT:
    obj1’s Size = 8
    obj1’s Address = 0012FF78
    obj2’s Size = 12
    obj2’s Address = 0012FF6C
    Example 3: Memory layout If we have one virtual function.

    OUTPUT:
    obj’s Size = 8
    obj’s Address = 0012FF7C
    Note: Adding one virtual function in a class takes 4 Byte extra.
    Example 4: More than one Virtual function

    OUTPUT:
    obj’s Size = 8
    obj’s Address = 0012FF7C
    Note: Adding more virtual functions in a class, no extra size taking i.e. Only one machine size taking(i.e. 4 byte)
    Example 5:

    OUTPUT:
       a = 200
       b = 10
    If we Change the code as then

    OUTPUT:
      a = 100
      b = 200
    Note: Who sits 1st place of Class : Answer is VPTR
               VPTR – 1st placed in class and rest sits after it.         
              

    Example 6:

    OUTPUT:
     VPTR’s Address 0012FF7C
     VPTR’s Value   0046C060
     
     NOTE: This VPTR’s value is a address of Virtual table. Lets see in next Example.
     
     Example 7:

    OUTPUT:
      VPTR’s Address                        0012FF7C
      VIRTUAL TABLE ‘s Address              0046C0EC
      Value at first entry of VIRTUAL TABLE 0040100A
      Test: fun1
     
    Example 8:

    OUTPUT:
      VPTR’s Address                        0012FF7C
      VIRTUAL TABLE ‘s Address              0046C0EC
      Value at first entry of VIRTUAL TABLE 0040100A
      Value at 2nd entry of VIRTUAL TABLE   004012

    Example :9

    OUTPUT:
    Test::fun1
    Test::func1
    Example 10: multiple Inheritance

    OUTPUT:
    Derive’s Size = 12

    Example 11: Calling Virtual Functions in case of Multiple Inheritance

    OUTPUT:
    Base1::fun
    Base1::func
    Base2::fun
    Base2::func
    Base3::fun
    Base3::func
    Drive::Fn
    Drive::Fncadministrator2008-01-27 11:34:41

  • #3322

    bharat123
    Member

    Hiin the example 10 of multiple inheritance ,i could’t understand the why the sizeof Derived class is 12 bytes, plz explain why this happening.
    waiting for ur reply……………

You must be logged in to reply to this topic.

0 Shares
Share
+1
Tweet
Share
Stumble