How do virtual functions work in C++ (vtable and vptr)?

The compiler makes one vtable for each class which has virtual functions. It is a table of function pointers. Each object gets a hidden pointer, the vptr, to the vtable of its real class. A virtual call follows the vptr to find the right function at run time.

You can see the cost of the hidden pointer in the size of the objects:

#include <iostream>

struct Plain   { int x; };
struct Virtual { int x; virtual void f() {} };

int main() {
    std::cout << sizeof(Plain) << ' ' << sizeof(Virtual) << '\n';
}
Output

4 16

On a 64 bit system the virtual class is bigger by the size of a pointer (and padded). A virtual call costs a little more than a normal call, and the compiler can often not put it inline. See Virtual Functions.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.