Main Content

MISRA C++:2023 Rule 15.1.1

An object's dynamic type shall not be used from within its constructor or destructor

Since R2024b

Description

Rule Definition

An object's dynamic type shall not be used from within its constructor or destructor.

Rationale

The type of an object during construction or destruction is the type of the currently executing constructor or destructor, which can be different from the type of the fully constructed object. If you use the dynamic type of an object inside a constructor or destructor, the object type can be different from what you expect.

In the case of a virtual call to a pure virtual function inside a constructor or destructor, the behavior is undefined. The called function can be undefined or can be overridden by the implementation of the currently running constructor or destructor instead of by the implementation of the most derived class.

Similarly, accessing the dynamic type of the current object (during construction or destruction) through a pointer or reference to a derived class results in undefined behavior. The pointed to object can be not fully constructed or already destroyed.

Polyspace Implementation

This coding rule checker reports a violation when you:

  • Use the this pointer in a constructor or destructor to:

    • Get the dynamic type of a polymorphic object using typeid().

    • Perform downcasting or run-time type checking using dynamic_cast().

  • Call a virtual function in a constructor or destructor or call a function that calls a virtual function in a constructor or destructor.

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>
#include <typeinfo>

class myClass
{
public:
    myClass()
    {
        // Check type of object being constructed
        std::cout << "Constructing a " <<
            typeid(*this).name() << "\n"; // Noncompliant

        // virtual call
        virtualCall();                    // Noncompliant
        // Other member definitions
    }

    virtual void virtualCall()
    {
    }

    virtual ~myClass() {}
};

In this example, the constructor inside the polymorphic class myClass queries the type of the object being constructed by using typeid() and calls the virtual function virtualCall(). Polyspace reports violations on these operations.

  • The type returned by typeid() is myClass. If the object is constructed in a derived class, the type of the object after the most derived class has completed can be different from the type returned by typeid().

  • The call to virtualCall() calls the function before it is defined, which results in undefined behavior. The function is defined only after the constructor completes.

Check Information

Group: Special member functions
Category: Required

Version History

Introduced in R2024b