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 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.

Pure Virtual Functions

Learn how to create interfaces and abstract classes using pure virtual functions

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Pure Virtual vs Virtual
What is the difference between a pure virtual function and a regular virtual function?
Pure Virtual Function Necessity
Can you provide an example of a situation where a pure virtual function would be necessary?
Advantages of Pure Virtual Functions
What are the advantages and disadvantages of using pure virtual functions?
Constructor in Abstract Class
Can you have a constructor in an abstract class? If yes, what is its purpose?
Vtable and Virtual Functions
What is a vtable, and how is it related to virtual functions?
Interfaces in Other Languages
What are the differences between interfaces in C++ and those in other programming languages like Java?
Design Patterns with Abstract Classes
What are some common design patterns that utilize abstract classes and interfaces?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant