Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class with virtual functions takes more space

Tags:

c++

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?

like image 797
scdmb Avatar asked Dec 10 '22 06:12

scdmb


1 Answers

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

like image 197
Mysticial Avatar answered Dec 31 '22 12:12

Mysticial