Lets say there is a class named Person which contains a virtual function named age(). As per language semantics, vtable is per class and not per object. It is VPTR which is per object and points to vtable.
Questions:
If I build this program (lets say main() exist):
-
Will the vtable be created i.e can vtable comes in existence w/o even creating a single object?
-
The address which is put by compiler in vtable for age() is a kind of some static address in memory?
-
Or is it that compiler internally creates some object for obtaining the address to age() (since age() will be working on some data members which can come in existence only when an object is constructed) or there is some other magic behind this?
As per my understanding, the answers are as follows:
- Yes
- Yes
- Not sure
I tried running “nm” on above program just to see if I can figure out the vtable, but no luck. Is there a way to do so?
Please suggest.
“As per language semantics,” there’s no such thing as a vtable. The C++ specification does not specify exactly how virtual dispatch is implemented. A compiler could use vtables. Or it could use something else; that’s up to the compiler.
A specific compiler can use vtables of course. But it can do whatever it wants with them; that’s an implementation detail. In short, there’s no way for you to know without investigating the specific compiler you’re using.
And really, does it matter that much?