Answer the question
In order to leave comments, you need to log in
How do virtual function table pointers work?
TL;DR
I decided to study the arrangement of virtual function tables, because I heard that this can be asked at the interview.
Naturally began to experiment with class size for interest. By itself, there was a tricky example, which gave rise to my question.
I note right away that I compile only with GCC and try to adhere to the standard. I generally understand how memory is managed when creating/deleting class objects. But I didn’t find a word in the standard about how the table of virtual functions is created in this case.
Description of the problem
We have an empty class. According to the c++ standard, the size of its objects will be equal to the minimum addressable unit - 1 byte.
After adding the virtual function, the size of the object will already be equal to 4 bytes - the size of the pointer to the table of virtual functions.
class A
{
//sizeof(BaseA) = 1 byte
}
class B
{
virtual void foo() {...}
//sizeof(B) = 4 byte
}
class BaseA
{
virtual void foo()
{
}
};
class BaseB
{
virtual void foo()
{
}
};
class Derived : BaseA, BaseB
{
};
sizeof(Derived) = 8
#include <iostream>
using namespace std;
class BaseA
{
virtual void foo()
{
}
};
class BaseB
{
virtual void foo()
{
}
};
class DerivedWithVirtual : BaseA, BaseB
{
virtual void bar()
{
}
};
class DerivedWithoutVirtual : BaseA, BaseB
{
};
int main()
{
cout << "Size of Base class A: "
<< sizeof(BaseA) << endl;
cout << "Size of Base class B: "
<< sizeof(BaseB) << endl;
cout << "Size of derived class with virtual function: "
<< sizeof(DerivedWithVirtual) << endl;
cout << "Size of derived class without virtual function: "
<< sizeof(DerivedWithoutVirtual) << endl;
system("pause");
return 0;
}
Size of Base class A: 4
Size of Base class B: 4
Size of derived class with virtual function: 8
Size of derived class without virtual function: 8
Answer the question
In order to leave comments, you need to log in
I try to adhere to the standard, but in 11 I did not find a word about how the table of virtual functions is created in such casesFrom the point of view of the standard, the table of virtual functions does not exist, but the function is chosen by magic.
struct base
{
virtual void foo() {}
};
struct derived: base
{
virtual void bar() {}
};
std::cout << sizeof(base) << '\n'
<< sizeof(derived) << '\n'
(representing a 32-bit machine and 4-byte pointers)4
4
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question