Pure Virtual Functions

Abstract Class Non-Virtual Functions

Can an abstract class have non-virtual member functions?

Abstract art representing computer programming

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.

This Question is from the Lesson:

Pure Virtual Functions

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

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Pure Virtual Functions

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

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved