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 function GetName()
and a non-virtual function PrintWelcomeMessage()
.PrintWelcomeMessage()
calls the pure virtual function GetName()
, ensuring the message includes the specific name of the derived class.Warrior
is a concrete class that provides an implementation of the GetName()
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.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to create interfaces and abstract classes using pure virtual functions