开发者

class with virtual functions takes more space

开发者 https://www.devze.com 2023-04-05 07:06 出处:网络
There is such code: #include <iostream> class A{ int a; int fun(){} }开发者_开发技巧; class B{

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

精彩评论

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