A virtual function is a function in a base class that can be overridden in derived classes. The keyword “virtual” allows runtime polymorphism in C++. When a derived class overrides a virtual function, the object uses the derived class implementation, even if it’s referred to as a base class object.
In contrast, a pure virtual function is a virtual function that has no definition in the base class. Declared using “= 0”, it enforces that derived classes must override the function. A class with a pure virtual function becomes an abstract class and cannot be instantiated.
Pure virtual functions are useful in designing class hierarchies where base classes define interfaces, and derived classes implement the functionality.
// Example of virtual and pure virtual functions
#include
using namespace std;
class Animal {
public:
virtual void sound() {
cout << "Animal sound" << endl;
}
virtual void move() = 0; // Pure virtual function
};
class Dog : public Animal {
public:
void sound() override {
cout << "Woof Woof" << endl;
}
void move() override {
cout << "The dog runs" << endl;
}
};
int main() {
Animal* a = new Dog();
a->sound(); // Woof Woof
a->move(); // The dog runs
delete a;
return 0;
}
Leave a Reply