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 Incorrect, as class methods are not stored inside the object as explained here]C-tor / D-tor
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;
}