Search code examples
c++vtable

understanding exactly how an object is mapped in memory


I read this question and some others regarding the layout of on object, but I still don't get exactly how it looks like.

Here are my specific question:

For each class (meaning that if I have a 2 super-classed I would have 2 pointers), virtual functions have 1 vtable pointer for them. where is it inside the object? Assuming the following: class A{void virtual f(){}; int x;}; would the address of an object A a be the same as the address of a.x or of a.f [or maybe point to a default method such as the C-tor / D-tor Incorrect, as class methods are not stored inside the object as explained here]

Example:

    class A{
    int x;
    void f(){}
    void virtual g(){}
    void virtual h(){}
};

A a;
std::cout << sizeof a; // result = 8

class A{
    int x;
    void f(){}
    void virtual g(){}
};

A a;
std::cout << sizeof a; // result = 8

class A{
    int x;
    void f(){}
    //void virtual g(){}
};

A a;
std::cout << sizeof a; // result = 4

From these examples it can be seen that when encountering a number (n > 0) of virtual functions, a pointer (4-bytes, on my 32-bit machine) is added to the object. Would it be added before other data members?

What would be pointed by:

A a;
int *p = (int*)&a;

I checked it out with this. Is it right to assume from the following that the vtable pointer always precedes other class members?:

class A{
public:
    A(int y){x=y;}
    virtual void g(){}
    int x;
    virtual void f(){}
};

int main ()
{
    A a(42);
    int *p = (int*)&a;
    std::cout << *p << std::endl;      // = 4215116 (vtable address?)
    std::cout << *(p+1) << std::endl;  // = 42
    return 0;
}

Solution

  • This is purely implementation dependent(compilers) and most of the implementations tend to go with inserting vptr as the first element. Since it is the first element and beginning of the object address, indirection for the virtual function call invocation will be easier as there is no further offset calculation to identify the vptr. Similar questions be asked in stackoverflow before and found the below one is useful. Why is vptr stored as the first entry in the memory of a class with virtual functions?