Pure Virtual Functions

Pure Virtual Function Necessity

Can you provide an example of a situation where a pure virtual function would be necessary?

Abstract art representing computer programming

Pure virtual functions are necessary when you want to define an interface that must be implemented by derived classes.

This is especially useful in designing frameworks or libraries where you want to ensure that certain functions are always implemented in the derived classes, providing specific behaviors.

For instance, imagine you are creating a game with different types of characters, and each character type must have a unique attack method.

You can define a pure virtual function in a base class Character to enforce this requirement:

#include <iostream>
#include <string>

// Base class with a pure virtual function
class Character {
public:
  virtual void Attack() = 0; 
};

class Warrior : public Character {
public:
  void Attack() override {
    std::cout << "Warrior attacks with a sword!\n";
  }
};

class Mage : public Character {
public:
  void Attack() override {
    std::cout << "Mage casts a fireball!\n";
  }
};

int main() {
  Warrior warrior;
  Mage mage;

  warrior.Attack(); 
  mage.Attack(); 
}
Warrior attacks with a sword!
Mage casts a fireball!

In this example:

  • Character has a pure virtual function Attack(). This means Character is an abstract class, and you cannot instantiate it directly.
  • Warrior and Mage are derived classes that must provide an implementation of the Attack() function. Each class defines its unique attack behavior.

Using pure virtual functions ensures that every derived class implements the Attack() method, providing the required behavior.

This design is essential when you want to enforce a specific interface across different classes, ensuring they adhere to a common contract.

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