Main Content

MISRA C++:2023 Rule 13.3.4

A comparison of a potentially virtual pointer to member function shall only be with nullptr

Since R2024b

Description

Rule Definition

A comparison of a potentially virtual pointer to member function shall only be with nullptr.

Rationale

When you compare a potentially virtual pointer to a member function with anything other than a nullptr, the result is unspecified.

For the purposes of this rule, a pointer to a member function is potentially virtual if any of these are true:

  • The pointer is declared with the constexpr keyword, making it a compile-time constant, and points to the address of a virtual member function.

  • The pointed to function is a member of a class that is not defined in the translation unit.

  • The pointer is not declared with the constexpr keyword, points to a member function a class, and the type of the pointer matches the type of a virtual member function in that class.

Polyspace Implementation

The coding rule checkers reports a violation when a pointer points to a member function that is or might be 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

#include <iostream>

class Base
{
public:
    void func() {}
    int func1() {}
    virtual void virtualFunc() {}
};

class Derived : public Base
{
public:
    void func2() {}
    int func3() {}
};

void checkPtr(void (Derived::*funcPtr)(), int (Derived::*funcPtr1)())
{

    if (funcPtr != nullptr)
    {
        std::cout << "Pointer is valid\n";
    }
    if (funcPtr1 != nullptr)
    {
        std::cout << "Pointer is valid\n";
    }
    if (funcPtr1 == &Derived::func3)
    {
        std::cout << "Pointer matches Derived::func2\n";
    }
    if (funcPtr == &Derived::func2)   // Noncompliant
    {
        std::cout << "Pointer matches Derived::func2\n";
    }
}

In this example, Polyspace reports a violation on the comparison funcPtr == &Derived::func2 because funcPtr is a potentially virtual pointer, making the result of the comparison unspecified.

funcPtr is a void pointer the member functions of the class Derived, and the pointer might point to the virtual member function virtualFunc with the same type as funcPtr, and which the class Derived inherits from the class Base.

The other pointer comparisons are all compliant because they are comparisons to nullptr, or in the case of funcPtr1 == &Derived::func3, there are no virtual member function in the class Derived that match the type of funcPtr1, so the pointer is not potentially virtual.

Check Information

Group: Derived classes
Category: Required

Version History

Introduced in R2024b