What is a virtual function in C++?
A virtual function is a member function you mark with the virtual keyword so that the correct version is chosen at run time based on the actual object, not the pointer type. This is how C++ achieves run time polymorphism. It lets a base class pointer call the derived class version of a function.
- A virtual function is chosen at run time based on the actual object, not the pointer type.
- It is how C++ achieves run time polymorphism through a base class pointer.
- A base class with virtual functions should also have a virtual destructor.
Why it matters
Without virtual, calling a function through a base pointer uses the base version. With virtual, C++ looks up the real object's type at run time and calls its version, which is essential for polymorphic designs.
class Animal {
public:
virtual void sound() { std::cout << "..."; }
};
class Dog : public Animal {
public:
void sound() override { std::cout << "woof"; }
};
Animal* a = new Dog();
a->sound(); // prints woof, thanks to virtual// In Java every method is virtual by default
class Animal {
void sound() { System.out.println("..."); }
}
class Dog extends Animal {
@Override
void sound() { System.out.println("woof"); }
}
Animal a = new Dog();
a.sound(); // prints woof
# In Python methods are virtual by default
class Animal:
def sound(self):
print("...")
class Dog(Animal):
def sound(self):
print("woof")
a = Dog()
a.sound() # prints woofMention the vtable, a hidden table of function pointers the compiler uses to resolve virtual calls at run time. Also stress that a base class with virtual functions should have a virtual destructor, a favourite follow up.
Frequently asked questions
What is a vtable?
It is a hidden table of function pointers the compiler builds for classes with virtual functions, used to look up the correct override at run time.
Why do you need a virtual destructor?
So that deleting a derived object through a base pointer calls the derived destructor. Without it, only the base destructor runs and resources leak.
Common follow up questions
Related interview questions
Want the full C++ guide?
Read every C++ concept with notes, diagrams, and code in one place. Track your progress as you go.
Open the C++ guide All C++ questions