Pure Virtual Functions

Pure Virtual vs Virtual

What is the difference between a pure virtual function and a regular virtual function?

Abstract art representing computer programming

A regular virtual function is a member function that you can override in derived classes to provide specific implementations.

When a function is marked as virtual in the base class, it allows derived classes to override it, providing different behavior for each derived type.

A pure virtual function, on the other hand, is a function that has no implementation in the base class and must be overridden in any derived class.

This is done by assigning the function to 0 in the base class. Pure virtual functions make the base class abstract, meaning you cannot create objects of this class directly.

Here’s an example:

#include <iostream>
#include <string>

class Character {
public:
  virtual std::string GetTaunt() {
    return "???";
  }
  virtual std::string GetName() = 0; 
};

class Orc : public Character {
public:
  std::string GetTaunt() override {
    return "Come get some!";
  }
  std::string GetName() override {
    return "Orc";
  }
};

int main() {
  Orc basher;
  std::cout << basher.GetName() << ": "
    << basher.GetTaunt() << "\n";
}
Orc: Come get some!

In this example:

  • GetTaunt() is a regular virtual function. It has a default implementation in the Character class but can be overridden in derived classes.
  • GetName() is a pure virtual function. It does not have an implementation in the Character class and must be overridden in derived classes.

Pure virtual functions enforce a contract that derived classes must adhere to, ensuring they provide specific functionality. Regular virtual functions allow base classes to provide default behavior while still allowing derived classes to override that behavior.

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