A regular virtual function is a member function that you can override in derived classes to provide specific implementations.
When a function is marked as virtual in the base class, it allows derived classes to override it, providing different behavior for each derived type.
A pure virtual function, on the other hand, is a function that has no implementation in the base class and must be overridden in any derived class.
This is done by assigning the function to 0 in the base class. Pure virtual functions make the base class abstract, meaning you cannot create objects of this class directly.
Here’s an example:
#include <iostream>
#include <string>
class Character {
public:
virtual std::string GetTaunt() {
return "???";
}
virtual std::string GetName() = 0;
};
class Orc : public Character {
public:
std::string GetTaunt() override {
return "Come get some!";
}
std::string GetName() override {
return "Orc";
}
};
int main() {
Orc basher;
std::cout << basher.GetName() << ": "
<< basher.GetTaunt() << "\n";
}
Orc: Come get some!
In this example:
GetTaunt()
is a regular virtual function. It has a default implementation in the Character
class but can be overridden in derived classes.GetName()
is a pure virtual function. It does not have an implementation in the Character
class and must be overridden in derived classes.Pure virtual functions enforce a contract that derived classes must adhere to, ensuring they provide specific functionality. Regular virtual functions allow base classes to provide default behavior while still allowing derived classes to override that behavior.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to create interfaces and abstract classes using pure virtual functions