Pure Virtual vs Virtual

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

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.

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 Function Necessity
Can you provide an example of a situation where a pure virtual function would be necessary?
Abstract Class Non-Virtual Functions
Can an abstract class have non-virtual member functions?
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