A virtual function is a member function declared with the virtual keyword in a base class and overridden in a derived class. It enables runtime polymorphism by allowing the appropriate function to be selected based on the actual object type.
- Enables dynamic function dispatch through base class pointers and references.
- Allows derived classes to provide their own implementation of inherited functions.
- Forms the foundation of runtime polymorphism in C++.
#include <iostream>
using namespace std;
class Animal{
public:
// Virtual function
virtual void sound() {
cout << "Animal makes a sound" << endl;
}
};
class Dog : public Animal{
public:
// Override the virtual function
void sound() override {
cout << "Dog barks" << endl;
}
};
int main(){
// Base class pointer pointing to derived class object
Animal* a = new Dog();
// Calls Dog's sound() due to virtual function
a->sound();
delete a; // Free allocated memory
return 0;
}
Output
Dog barks
Explanation:
- virtual function: The sound() function in the Animal class is declared as virtual.
- Function overriding: The Dog class provides its own version of the sound() function.
- Base class pointer: The Animal* pointer points to a Dog object.
- Runtime polymorphism: a->sound() calls the Dog class's function at runtime.
Note: Using the override specifier is recommended because the compiler can detect if the derived function does not correctly override a base class virtual function.
Pure Virtual Function
A pure virtual function is declared by assigning = 0 to a virtual function. It makes the class abstract and requires derived classes to provide an implementation.
- A class containing at least one pure virtual function is an abstract class and cannot be instantiated.
- A derived class must override all inherited pure virtual functions to become a concrete class.
- A pure virtual destructor must still have a definition if it is declared in the base class.
#include <iostream>
using namespace std;
class Base
{
public:
// Pure virtual function
virtual void display() = 0;
// Pure virtual destructor
virtual ~Base() = 0;
};
// Definition of pure virtual destructor
Base::~Base()
{
cout << "Base destructor called" << endl;
}
class Derived : public Base
{
public:
void display() override
{
cout << "Derived class display" << endl;
}
~Derived()
{
cout << "Derived destructor called" << endl;