If you have an object of a class that has virtual functions, and this object is not a pointer, will the virtual method table be used?
E.g let's pretend that the class Student
has a virtual function GetGrade()
. Since my_student
is not a pointer to the polymorphic class, will virtual method tables be used?
Student my_student{};
my_student.GetGrade();
I was expecting the vtable to be consulted when I tried this, but it didn't happen.
This is a simple case of devirtualization, or "calling the correct function without reading the vtable". It is an optimization: the code does the same but faster. The compiler is allowed to perform any optimizations on your code, and many compilers do this.
In this specific case, it's easy (for the compiler) to prove that the runtime type of my_student
is Student
: the runtime type is the same as the static type, because it's an object and not a pointer. Even if it was a pointer, it could still do this optimization in the following case:
Student* my_student{new Student};
my_student->GetGrade();
Here, there is no chance for *my_student
to have any other type than Student
. However, if the creation and the usage of the object are not nearby in the code, the optimization can't be performed.
Student* my_student{};
if (special)
my_student = new SpecialStudent;
else
my_student = new Student;
my_student->GetGrade();
Of course, where you really need polymorphism, no devirtualization can be performed. Conversely, if the compiler performs devirtualization, you should think whether you need virtual functions at all.