开发者

class with virtual functions takes more space

There is such code:

#include <iostream>

class A{
    int a;
    int fun(){}
}开发者_开发技巧;

class B{
    int a;
    virtual int fun(){}
};

int main()
{
    std::cout << sizeof(A) << " " << sizeof(B) << std::endl;
    std::cin.get();
    return 0;
}

The output is:

4 8

Why class B is 4 bytes bigger than class A?


Any class with a virtual function needs a pointer to the vtable for that class. Therefore, there is a hidden member that's the size of the pointer.

http://en.wikipedia.org/wiki/Virtual_method_table

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜