You are here:

C++/When is VTABLE created


QUESTION: When is a vtable created: compile time or run time. In particular, if a declare a class having one or more virtual functions, and in first case I create an object of it and in second case I don't create an object. What difference it makes in terms of number of vtables created.

ANSWER: A vtable is created in an instance of a class when the base class has one or more virtual functions.  The object of the class doesn't need a vtable because this object will call it's member functions.  An object subclassed off the object with virtual functions will have a vtable so that at runtime, an object of this class will use it's member function and not the base classes.

This is a pretty good description if you trust wikipedia.


---------- FOLLOW-UP ----------

QUESTION: Thanks for the reply.

Does that mean that a VTABLE is created per class, no matter their object is created or not; considering only classes having virtual functions and those derived from them.


You're welcome.  A vtable is created per *object*, because only at runtime will the object know if it the subclassed class or base class.  This could be a lot of memory if you have 10000 objects of a class with virtual functions, but for normal data demands, you'll never have to worry about the extra memory.



All Answers

Answers by Expert:

Ask Experts


Bill A


I can answer questions about C++, programming algorithms, Windows programming in MFC (which is C++). I cannot answer questions about STL (templates) and I have no experience with Linux. I do enjoy reviewing code and critiquing it or finding problems in it. I will also gladly show better algorithms or methods if you want to take advantage of that.


I've developed a commercial embedded C compiler/assembler and IDE with debugger toolset, of which the IDE and debugger are written in C++. I work in the industry writing high tech embedded programs and Windows programs to communicate with the embedded devices.

Book: Embedded Systems Design using the Rabbit 3000 Microprocessor Authored Chapter 10 in its entirety.

BS Computer Engineering

©2017 All rights reserved.