How is virtual inheritance implemented in memory using a C ++ compiler?

The VIRTUAL keyword puzzles me. I am trying to find how the compiler implements this in memory. ok let me explain with examples. I am using Microsoft Visual Studio 2010 because the implementation of the virtual is compiler dependent.

here is the first code

#include<iostream>
class one
{
    int _a;
public:
    virtual ~one(){}
};
class two:public one
{
    int _a;
public:
    virtual ~two(){}
};

int main()
{
    using namespace std;
    cout<<"sizeof two="<<sizeof(two)<<endl;
    return 0;
}

o / p - 12 bytes, due to _vptr_two, one :: _ a and two :: _ a

here is another code example

#include<iostream>
class one
{
    int _a;
public:
    virtual ~one(){}
};
class two
{
    int _a;
public:
    virtual ~two(){}
};
class three:virtual public one,virtual public two
{
};

int main()
{
    using namespace std;
    cout<<"sizeof three="<<sizeof(three)<<endl;
    return 0;
}

in this case, o / p is 20 bytes: O, how did it happen? Please explain !! For me, this should be 16 bytes. __vptr_three (pointer to vtable), _vptr1_three (pointer to the virtual base class table), one :: _ a and two :: _ a. And why is a virtual base class table supported?

+4
2

pdf , , V++, .

class three,

00A516BD  cmp         dword ptr [ebp+8],0 
00A516C1  je          three::three+60h (0A516F0h) 
00A516C3  mov         eax,dword ptr [this] 
00A516C6  mov         dword ptr [eax],offset three::`vbtable' (0A57828h) => 4 Bytes
00A516CC  mov         ecx,dword ptr [this] 
00A516CF  add         ecx,8 
00A516D2  call        one::one (0A51253h) 
00A516D7  or          dword ptr [ebp-0D4h],1 
00A516DE  mov         ecx,dword ptr [this] 
00A516E1  add         ecx,10h 
00A516E4  call        two::two (0A512BCh) 
00A516E9  or          dword ptr [ebp-0D4h],2 
00A516F0  mov         eax,dword ptr [this] 
00A516F3  mov         ecx,dword ptr [eax] 
00A516F5  mov         edx,dword ptr [ecx+4] 
00A516F8  mov         eax,dword ptr [this] 
00A516FB  mov         dword ptr [eax+edx],offset three::`vftable' (0A57820h)  => 4 Bytes
00A51702  mov         eax,dword ptr [this] 
00A51705  mov         ecx,dword ptr [eax] 
00A51707  mov         edx,dword ptr [ecx+8] 
00A5170A  mov         eax,dword ptr [this] 
00A5170D  mov         dword ptr [eax+edx],offset three::`vftable' (0A57814h)   => 4 Bytes
00A51714  mov         eax,dword ptr [this] 
00A51717  pop         edi  
00A51718  pop         esi  
00A51719  pop         ebx  
00A5171A  add         esp,0D8h 

,
4 (vbtable)
2 4 * 2 = 8 , (vftable)
one::_a 4
two::_a 4

, 20 . pdf (. 17) :

" Visual ++, P vftable-, T, vftable, vfptr, T."

+7

, , ( , ), .

, three ( 4 ): " ", three, , one, , two.

3 * 4 2 * 4 int , 20 .

, 64- ( 8- ), - : 32 , , , , , int.

+2

Source: https://habr.com/ru/post/1527829/


All Articles