I’m keen to know exactly how the classes will be arranged in memory esp. with inheritance and virtual functions.
I know that this is not defined by the c++ language standard. However, is there any easy way to find out how your specific compiler will implement these say by writing some test code?
EDIT:- Using some of the answers below :-
#include <iostream>
using namespace std;
class A {
public:
int a;
virtual void func() {}
};
class B : public A {
public:
int b;
virtual void func() {}
};
class C {
public:
int c;
virtual void func() {}
};
class D : public A, public C {
public:
int d;
virtual void func() {}
};
class E : public C, public A {
public:
int e;
virtual void func() {}
};
class F : public A {
public:
int f;
virtual void func() {}
};
class G : public B, public F {
public:
int g;
virtual void func() {}
};
int main() {
A a; B b; C c; D d; E e; F f; G g;
cout<<"A: "<<(size_t)&a.a-(size_t)&a<<"\n";
cout<<"B: "<<(size_t)&b.a-(size_t)&b<<" "<<(size_t)&b.b-(size_t)&b<<"\n";
cout<<"C: "<<(size_t)&c.c-(size_t)&c<<"\n";
cout<<"D: "<<(size_t)&d.a-(size_t)&d<<" "<<(size_t)&d.c-(size_t)&d<<" "<<(size_t)&d.d- (size_t)&d<<"\n";
cout<<"E: "<<(size_t)&e.a-(size_t)&e<<" "<<(size_t)&e.c-(size_t)&e<<" "<<(size_t)&e.e- (size_t)&e<<"\n";
cout<<"F: "<<(size_t)&f.a-(size_t)&f<<" "<<(size_t)&f.f-(size_t)&f<<"\n";
cout<<"G: "<<(size_t)&g.B::a-(size_t)&g<<" "<<(size_t)&g.F::a-(size_t)&g<<" " <<(size_t)&g.b-(size_t)&g<<" "<<(size_t)&g.f-(size_t)&g<<" "<<(size_t)&g.g-(size_t)&g<<"\n";
}
And the output is :-
A: 8
B: 8 12
C: 8
D: 8 24 28
E: 24 8 28
F: 8 12
G: 8 24 12 28 32
So all classes have got a v-ptr at loc 0 of size 8.
D has another v-ptr at location 16. Similarly for E.
G also seems to have a v-ptr at 16 although from my (limited) understanding I would have guessed it to have more.
One way is to print out the offsets of all the members:
Output:
So you can see all the offsets here. You’ll notice that there’s nothing at offset 0, as that is presumably where the pointer to the vtable goes.
Also notice that the inherited members have the same offsets in both Child and Parent.