Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Below is a pseudo declaration for a multilevel inheritance. Base class ( protect

ID: 655527 • Letter: B

Question

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).
Does size also include virtual tables also. Again here there cannot be virtual table as no virtual function defined. Please help in clarifying my doubt.

PS: What I have understood till now:

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().

Explanation / Answer

The question you ask has no answer in the C++ standard. Compilers are free to insert additional members into classes for reasons of multiple inheritance, virtual, access control, alignment and so on. I think I would expect an additional item for a virtual base class, but I haven't investigated it specifically.

In practice you can expect a single pointer rather than a whole virtual table, and reasonably predictable padding. Beyond that I would hesitate to generalise.

If you really want to know why a specific structure you wrote has the specific sizes they do then you might use the debugger to find out what actually gets stored in each location. Any programs written to take advantage of that information would of course be non-portable.

Your supposition is correct but (a) that's a down-cast which has to be explicit (b) virtual function is not the same as virtual base class.

BTW it's called multiple inheritance.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote