Size of objects in multi-level / multiple inheritance

Below is a pseudo declaration for a multilevel inheritance.

Base class ( protected int data)

derived1 : virtual public base ( protected int data1 )

derived2 : virtual public base ( protected int data2)

derived3 : derived1,derived2 ( private int data3 )

Main(){ base b;    derived1 d1;   derived2 d2;   derived3 d3; }

sizeof(b) // 4 which is correct as only int (4bytes)
sizeof(d1) // 12 why not 8 -> 4(base) + 4(derived)
sizeof(d2) // ??? whatever applies above should apply here
sizeof(d3) // 24 why not 12 -> 4(base) + 4(derived1/derived2) + 4(d3).

In addition, size also includes virtual tables. Again, there cannot be a virtual table, since no virtual function is defined. Please help clarify my doubts.

PS: What I understood so far:

Unless the function is declared virtual in base class,

base *bptr;
 derived d;
 bptr = &d;
 bptr->fun();  // will call the base class function.

But if the fun() is declared virtual then the above code will call derived class fun().
0
source share
1 answer

First of all, in your implementation above you should return a type countinstead void.

For example, suppose you announced int count.

Then you need to return intin the version of 'postfix' and int&or const int&in the version of 'prefix'.

b = a++ b = ++a, (, , ).

. "c++" count , "postfix ++" count .

, "c++" (, int), "c++" (, int&).

, .

+1

All Articles