Using virtual functions in C++ does have a slight performance impact compared to non-virtual functions. This is due to the way virtual function calls are resolved at runtime.
When a function is declared as virtual, the compiler creates a virtual function table (vtable) for each class that contains virtual functions. The vtable is an array of function pointers that point to the virtual functions of the class. Each object of the class contains a hidden pointer (vptr) that points to the vtable.
When a virtual function is called through a pointer or reference to a base class, the program uses the vptr to look up the correct function to call in the vtable. This lookup and indirection adds a small overhead compared to a direct function call.
However, it's important to note that the performance impact of virtual functions is usually negligible in most scenarios. The benefits of polymorphism and code flexibility often outweigh the slight performance cost.
Consider the following example:
#include <iostream>
class Monster {
public:
virtual void attack() {
std::cout << "Monster attacks!\n"; }
};
class Dragon : public Monster {
public:
void attack() override {
std::cout << "Dragon breathes fire!\n"; }
};
int main() {
Monster* monster = new Monster();
Monster* dragon = new Dragon();
monster->attack();
dragon->attack();
delete monster;
delete dragon;
}
Monster attacks!
Dragon breathes fire!
In this example, the virtual function attack()
allows for runtime polymorphism. The performance impact of the virtual function call is minimal compared to the benefits of being able to treat Monster
and Dragon
objects polymorphically.
It's generally recommended to use virtual functions when you need runtime polymorphism and to avoid them when you don't. Premature optimization should be avoided, and the focus should be on writing clear, maintainable, and flexible code.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to write flexible and extensible C++ code using polymorphism, virtual functions, and dynamic casting