No InheritanceOutput:
- class A
- {
- public:
- int a;
- };
- class B
- {
- public:
- int b;
- };
- class C: public A, public B
- {
- public:
- int c;
- };
- void main()
- {
- C obj;
- cout << &obj << endl << &obj.a << endl << &obj.b << endl << &obj.c << endl;
- }
0012FF58
0012FF58
0012FF5C
0012FF60
if change the order of inheritance into:
class C : public B, public A
class C : public B, public A
0012FF58
0012FF5C
0012FF58
0012FF60
- The storage of a derived class is dependent on the declare order.
Single Inheritance
In the case that a virtual function is added to A:
- class A
- {
- public:
- int a;
- virtual void fA() {}
- };
- ...
- class C: public A, public B
- ...
Output:
0012FF54
0012FF58
0012FF5C
0012FF60
the new address of obj now is 0012FF54 instead of 0012FF58. First extra 4 bytes is used to for __vfptr. And one more thing, if I change the order of inheritance (don't remove the virtual function in A), the output does not change (!!!).
- It seems that in the multiple inheritance case, the class which contains virtual methodhas higher priority when being storaged.
Multiple Inheritance
Next, add a new virtual method to B and change to order of inheritance in turn, a C object now will contain two __vfptr corresponding with the A and B (or B and A up to the declaration order).
Output:
0012FF50
0012FF54
0012FF5C
0012FF60
- The number of __vfptrs which an object contains are up to the number of classes it inherits.
(To be continued ... )