A virtualfunction is a function in a base class that can be
overridden in derived classes. It allows runtime polymorphism — meaning the function that gets called is determined at runtime based on the
type of object being referred to, not the type of pointer or reference.
Why it is used
Virtual functions are used to:
Achieve runtime polymorphism (dynamic binding).
Allow derived classes to provide their own implementation of a base class method.
Make code flexible and extensible — you can add new derived types without changing existing code.
Syntax
In C++:
class Base {
public:
virtual void show() { // virtual function
cout << "Base class show function" << endl;
}
};
class Derived : public Base {
public:
void show() override { // override keyword is optional
cout << "Derived class show function" << endl;
}
};
Example — Without and With Virtual Function
Without virtual function:
#include <iostream>
using namespace std;
class Base {
public:
void show() { // Not virtual
cout << "Base class show" << endl;
}
};
class Derived : public Base {
public:
void show() {
cout << "Derived class show" << endl;
}
};
int main() {
Base* ptr;
Derived obj;
ptr = &obj;
ptr->show(); // Calls Base::show() because it's not virtual
return 0;
}
Output:
Base class show
With virtual function:
#include <iostream>
using namespace std;
class Base {
public:
virtual void show() { // Virtual function
cout << "Base class show" << endl;
}
};
class Derived : public Base {
public:
void show() override {
cout << "Derived class show" << endl;
}
};
int main() {
Base* ptr;
Derived obj;
ptr = &obj;
ptr->show(); // Calls Derived::show() because of virtual function
return 0;
}
Output:
Derived class show
Key Points:
Virtual functions must be declared in the base class using the
virtual keyword.
They enable late binding (runtime decision).
If a class has at least one virtual function, it should have a virtual destructor to ensure proper cleanup.
The override keyword (C++11 onward) ensures that the function actually overrides a base class virtual function.
Virtual functions are implemented internally using a vtable (virtual table).
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Why it is used
Virtual functions are used to:
Syntax
In C++:
Example — Without and With Virtual Function
Without virtual function:
Output:
With virtual function:
Output:
Key Points:
virtualkeyword.overridekeyword (C++11 onward) ensures that the function actually overrides a base class virtual function.