If i have a to call x virtual function on the same object, will the compiler be smart enough to somehow remember the vtable address or it will dig the address on each x call? Cheers
2 Answers
Whenever there is a virtual function inside definition of a class either through inheritance or normal declaration a vtable is created.
Vtables themselves are generally stored in the static data segment as they are class specific as compared to object specific.Generally whenever an object of a class is created vtable pointer pointing to the vtable of the class is generally stored in the beginning of the object's memory location but it depends on the compiler in the end how it implements the virtual function.
Now as long as the object remains in the memory, It includes pointer to its Vtable.So if you call the virtual function on the same object ,just the pointer to vtable is referenced to get vtable location.No digging of address is required.

- 1,321
- 2
- 11
- 15
-
thanks. However which one might provide a better performance, a switch where i can identify and cast according to an enum (cost of the cast and the switch but all x call will be direct to the object) or accessing vtable for each x call (thus only the vtable access cost)? – user2463968 Apr 03 '15 at 12:51
-
Vtable just add one extra de-referencing for accessing the virtual function as compared to normal function call.So i don't think you will get a very good performance improvement by using switch and cast. – avinash pandey Apr 03 '15 at 13:08
There are several good answers to a similar question here: Cost of a virtual function in a tight loop
In general, to understand the C++ object model and the implementation choices Stroustrup made, I recommend his book "The design and evolution of the C++ language".

- 1
- 1

- 2,585
- 1
- 14
- 25
-
Well, that's exactly what i was look for. So the conclusion for me is to not worry about it either, specially with this answer http://stackoverflow.com/a/6599975/2463968 – user2463968 Apr 03 '15 at 13:01