0

The following code

    class B
{
public:
     void f1() {}
};
class C
{
public:
     void f2() {}
};
class D : public B, public C
{
public:
    virtual void f3() {}
};
int main()
{

    cout << sizeof(B) << endl;
    cout << sizeof(C) << endl;
    cout << sizeof(D) << endl;

    system("pause");
    return 0;
}

gets a result 1 1 8.So why is 8 not 4(in my computer,a pointer takes 4 bytes)? B,C do not have vptr, and when D has virtual members, D's Vptr is placed in the Vtable of the first inherited class which is B,since the following code

class B
{
public:
     virtual void f1() {} //now is virtual
};
class C
{
public:
     void f2() {}
};
class D : public B, public C
{
public:
    virtual void f3() {}
};
int main()
{

    cout << sizeof(B) << endl;
    cout << sizeof(C) << endl;
    cout << sizeof(D) << endl;

    system("pause");
    return 0;
}

gets a result 4,1,4. May somebody explain it to me, thanks a lot!

Shawn
  • 82
  • 4
  • I suspect that what you expect is reasonable by the language standard (i.e. both `B` and `C` should be able to share space with the vptr) , but the ABI implemented by your compiler doesn't work the same way that you have intuited. I.e. it's an ABI issue. – davmac Jan 29 '18 at 12:28
  • This might be helpful: https://stackoverflow.com/questions/2038717/object-size-with-virtual – Arnav Borborah Jan 29 '18 at 12:28
  • Thanks! So you mean that with different compilers it may get different results, both 8 and 4 are right. @davmac – Shawn Jan 29 '18 at 12:39
  • it's a different question, but thanks anyway! @ArnavBorborah – Shawn Jan 29 '18 at 12:41
  • 5
    Side note: There is nothing written about vtables at all in the C++ standard itself! If you find some clever solution to get this matter right completely without vtables, you are free to do so. vtables are a *de facto* standard just because they apparently are the most suitable solution found so far... (more precisely: *usage of some kind of* vtables is de facto standard, not their exact layout). – Aconcagua Jan 29 '18 at 12:44
  • 1
    @Shwan I mean that for different ABIs 8 and 4 could both be right. I'm distinguishing because compilers for a particular platform will generally use the same ABI, otherwise they would be incompatible. On Linux with GCC/Clang I see 1,1,4 for your first example. https://godbolt.org/g/8iDZmC – davmac Jan 29 '18 at 13:20

0 Answers0