Main Content

MISRA C++:2023 Rule 13.3.1

User-declared member functions shall use the virtual, override and final specifiers appropriately

Since R2024b

Description

Rule Definition

User-declared member functions shall use the virtual, override and final specifiers appropriately.

Rationale

To make the design of a class easy to understand, this rule specifies the appropriate use of the virtual, override, and final specifiers for user-declared member functions and destructors:

  • Use the specifier virtual if the member function is a new virtual function that does not override a function from a base class.

  • Use the specifier override if the member function is a virtual function that overrides a virtual function from a base class and permits further overrides in subsequent derived classes.

  • Use the specifier final if the member function is a virtual function that overrides a function from a base class and does not permit further overrides in subsequent derived classes.

Other combinations of these specifiers are permissible in the C++ standard but violate this rule because they can make the code harder to understand.

Polyspace Implementation

Polyspace® reports a violation if any of these conditions are true:

  • A virtual function in a derived class uses the specifier virtual in addition to override or final.

  • A virtual function in a base class uses the specifier override or final in addition to virtual.

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

In this example, the derived class Dog uses the specifier virtual in the definition of DOg::makeSound() in addition to the specifier override. This use of the of the virtual and override specifiers is permitted in the C++ standard but makes the code difficult to understand. Polyspace reports a violation.

#include <iostream>

// Base class
class Animal {
public:
    // Virtual function
    virtual void makeSound() const{
        std::cout << "Some generic animal sound" << std::endl;
    }

    // Virtual destructor
    virtual ~Animal() = default;
};

// Derived class 1
class Dog : public Animal {
public:
    // Override the virtual function
    virtual void makeSound() const override {  // Noncompliant
        std::cout << "Bark" << std::endl;
    }
};

// Derived class 2
class Cat : public Animal {
public:
    // Override the virtual function
    void makeSound() const override { //Compliant
        std::cout << "Meow" << std::endl;
    }
};

The derived virtual function Cat::makeSound() is compliant because it uses the specifier override.

Check Information

Group: Derived classes
Category: Required

Version History

Introduced in R2024b