Yes, virtual functions in C++ can have default implementations in the base class. This allows you to provide a fallback behavior for derived classes that don't override the virtual function.
When a virtual function has a default implementation in the base class, derived classes have the option to override it if they need specific behavior. If a derived class doesn't override the virtual function, the default implementation from the base class will be used.
Here's an example:
#include <iostream>
class Monster {
public:
virtual void attack() {
std::cout << "Monster attacks!\n"; }
};
class Dragon : public Monster {
public:
void attack() override {
std::cout << "Dragon breathes fire!\n"; }
};
class Orc : public Monster {
// Doesn't override attack()
};
int main() {
Monster* monster = new Monster();
Monster* dragon = new Dragon();
Monster* orc = new Orc();
monster->attack();
dragon->attack();
orc->attack();
delete monster;
delete dragon;
delete orc;
}
Monster attacks!
Dragon breathes fire!
Monster attacks!
In this example, the Monster
class provides a default implementation for the attack()
function. The Dragon
class overrides the attack()
function with its own implementation, while the Orc
class doesn't override it.
When orc->attack()
is called, since the Orc
class doesn't have its own implementation, the default implementation from the Monster
class is used.
Providing default implementations for virtual functions can be useful in several scenarios:
override
 keyword.However, it's important to note that if a virtual function is intended to be purely abstract and must be implemented by derived classes, you should declare it as a pure virtual function instead of providing a default implementation.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to write flexible and extensible C++ code using polymorphism, virtual functions, and dynamic casting