Main Content

AUTOSAR C++14 Rule A12-4-1

Destructor of a base class shall be public virtual, public override or protected non-virtual

Since R2020a

Description

Rule Definition

Destructor of a base class shall be public virtual, public override or protected non-virtual.

Rationale

If a base class destructor is not public virtual or public override, the class cannot behave polymorphically for deletion of derived class objects.

If a pointer to a base class refers to a derived class object and you use the pointer to delete the object:

class Base {
  public:
    ~Base() {}
};
    
class Derived: public Base {
  public:
    ~Derived() {}
};
...
void func(Base* ptr) {
    //ptr might point to a Base or Derived object
    delete ptr;
}
only the base class destructor is called. Additional resources allocated in the derived class are not released and can cause a resource leak. See example below.

If you want to prevent calling the derived class destructor through a base class pointer, make your intent explicit by making the destructor protected. Otherwise, it might appear that the possibility of polymorphic deletion of derived class objects was not considered.

Polyspace Implementation

The checker flags base classes with destructors that are not public virtual, public override or protected non-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 <new>

class Base {
  public:
    Base() {}
    ~Base() {} //Noncompliant
};
    
class Derived: public Base {
     int *arr;
  public:
     Derived() {
        arr = new int(5);
     }
    ~Derived() {
        delete arr;
     }
};

void main() {
    Base* basePtr = new Derived();
    delete basePtr;
}

In this example, the class Base has a non-virtual destructor. As a result, when the pointer basePtr is deleted, only the destructor of class Base is invoked. However, basePtr points to an object of class Derived. The deletion is not complete because the destructor of class Derived is not invoked. In particular, the data member arr in the derived object is not deleted.

Check Information

Group: Special member functions
Category: Required, Automated

Version History

Introduced in R2020a