Abstract Class Non-Virtual Functions
Can an abstract class have non-virtual member functions?
Yes, an abstract class can have non-virtual member functions. In fact, an abstract class can have a mix of pure virtual functions, regular virtual functions, and non-virtual functions.
Non-virtual functions in an abstract class are typically utility functions that provide common functionality to all derived classes, but they cannot be overridden.
Here's an example:
#include <iostream>
#include <string>
// Abstract base class with a mix of function types
class Character {
public:
virtual std::string GetName() = 0;
void PrintWelcomeMessage() {
std::cout << "Welcome, " << GetName() << "!\n";
}
};
class Warrior : public Character {
public:
std::string GetName() override {
return "Warrior";
}
};
int main() {
Warrior warrior;
warrior.PrintWelcomeMessage();
}
Welcome, Warrior!
In this example:
Character
is an abstract class with a pure virtual functionGetName()
and a non-virtual functionPrintWelcomeMessage()
.PrintWelcomeMessage()
calls the pure virtual functionGetName()
, ensuring the message includes the specific name of the derived class.Warrior
is a concrete class that provides an implementation of theGetName()
function.
The non-virtual function PrintWelcomeMessage()
can be used by all derived classes without the need for each class to implement its version.
This can reduce code duplication and provide common functionality across different types of characters.
Pure Virtual Functions
Learn how to create interfaces and abstract classes using pure virtual functions