+ 1

What is decided at run time in virtual function

Very basic question on polymorphism but still would like to ask: vtable is static array and it gets created at compile time... Also Vtable gets created per class involving one virtual method directly or indirectly Question is about what happens at run time ? Is it like vptr of object gets associated at run time ? If so, why not at compile time ? base* p = new derived; This line is known to compiler and why it does not directly associate the virtual table of derived class ?

29th Apr 2022, 5:15 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 Respostas
+ 2
Q. Question is about what happens at run time ? Is it like vptr of object gets associated at run time ? Indeed, when you write "base* p = new derived;", *p* pointer gets assigned to vptr of "derived" class and will start pointing to "derived" class's virtual table, so that function of correct class is called at runtime --- Q If so, why not at compile time ? At compile time, it is not always possible to correctly identify if the pointer is pointing to the base class or one of it's derived class, take the following case for example ``` void foo (base *p) { p->vfunc (); } ``` here, at compile time, it can't be said if the pointer *p* would be pointing to a base class or one of its derivatives. As a matter of fact, some compiler implementations do support de-virtualisation optimisations where if the compiler can precisely identify the correct function that is to be called at the call-site, it converts the polymorphic call to direct call. ( you can observe it by enabling -O2 optimisations on gcc and clang )
30th Apr 2022, 2:17 PM
Arsenic
Arsenic - avatar
+ 1
Thanks Arsenic
30th Apr 2022, 5:18 PM
Ketan Lalcheta
Ketan Lalcheta - avatar