0

Output is 8 16 24..how does it happened??

//given::sizeof(void*)=8 and sizeof(double)=8 #include<iostream> using namespace std; class A{ public: virtual void f()=0; }; class B :public A{ double data1; public: void f(){ cout<<"B::f()"; } }; class C:public A,public B{ double data2; public: void f(){ cout<<"c::f()"; } }; int main(){ cout<<sizeof(A)<<endl; cout<<sizeof(B)<<endl; cout<<sizeof(C)<<endl; }

12th Mar 2021, 7:40 AM
__n
__n - avatar
6 Réponses
+ 2
If the output *should* be 24 for the size of class C, then inheriting from class 'B' only is sufficient, since sizeof( B ) + sizeof( double ) = 24. Inheriting from both 'A' and 'B' is pointless anyway, due to the reasons described earlier.
13th Mar 2021, 10:00 AM
Shadow
Shadow - avatar
+ 1
Most compilers use a virtual function table (vtable) to implement dynamic polymorphism. This means that any object with a virtual function needs to store a pointer (void*, usually denoted vptr) to its vtable, this is how the compiler is able to figure out the correct method to call at runtime, even from pointers or references of the base class. That additional pointer is usually stored at the start of the object. Since sizeof( void* ) = sizeof( double) = 8, you therefore get the expected results. Additional examples with explanation: https://stackoverflow.com/questions/9439240/sizeof-class-with-int-function-virtual-function-in-c More about the vtable: https://stackoverflow.com/questions/3004501/why-do-we-need-virtual-table Why the vptr is associated with the object, not the class: https://stackoverflow.com/questions/13914178/why-vptr-is-not-static
12th Mar 2021, 9:45 AM
Shadow
Shadow - avatar
+ 1
Actually, it would be interesting to know where the 24 comes from. GCC 10.2.0 returns 32 for sizeof( C ) and warns about inaccessibility of 'A' due to ambiguity, since you inherit from 'A' twice, once explicitly and then implicitly from 'B'. It's somewhat similar to the diamond problem: https://en.m.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem
12th Mar 2021, 12:37 PM
Shadow
Shadow - avatar
+ 1
Shadow Thnx i understood
13th Mar 2021, 10:31 AM
__n
__n - avatar
0
Means for class A size is 8 (as given in question that void*=8) Size of B is sizeof(double data1)+(void function)=16..is it right?? Then for class C both A B are inherited so..how does calculation happens??
12th Mar 2021, 11:04 AM
__n
__n - avatar
0
Shadow ... actually it is a question that o/p should be 8 16 24...Given is::sizeof(void*)=8 and sizeof(double)
12th Mar 2021, 4:49 PM
__n
__n - avatar