Size of class with virtual function

拟墨画扇 提交于 2019-12-02 18:19:11

问题


I was revising the C++ concepts, but I am stuck with a very simple code

#include <iostream>
using namespace std;

class foo {
public:
    //int i;
    void virtual foobar()
    {
        cout << "foobar\n";
    }
};

int main()
{
    foo f;
    cout << sizeof(f) << endl;
    //cout << sizeof(f.i) << endl;
    return 1;
}

The output of the above code is 8 But when I removed comments from the code Output is 16 and 4

I did not understand when the class have no member variable present then VPTR size is 8 but after adding a variable size becomes 12.


回答1:


You're working on a platform where pointers are aligned to 8 bytes. Since the virtual table pointer is typically the first thing in the layout of an object, it too must be aligned to 8 bytes. So padding 4 bytes are inserted after the int member, that's why you get a size of 16 (8 bytes for the vf table pointer, 4 for the int and 4 padding bytes).



来源:https://stackoverflow.com/questions/22113519/size-of-class-with-virtual-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!