Edit

Share via


Warning C26436

The type 'symbol' with a virtual function needs either public virtual or protected non-virtual destructor (c.35)

C++ Core Guidelines: C.35: A base class destructor should be either public and virtual, or protected and nonvirtual

If a class defines a virtual function it becomes polymorphic, which implies that derived classes can change its behavior including resource management and destruction logic. Because client code may call polymorphic types via pointers to base classes, there's no way a client can explicitly choose which behavior is appropriate without downcasting. To make sure that resources are managed consistently and destruction occurs according to the actual type's rules, you should define a public virtual destructor. If the type hierarchy is designed to disallow client code to destroy objects directly, destructors should be defined as protected non-virtual.

Remarks

  • The warning shows up on the first virtual function definition of a type (it can be a virtual destructor if it isn't public), once per type.

  • Since a definition can be placed separately from a declaration, it may not always have any of the virtual specifiers. But the warning is still valid: it checks the actual 'virtuality' of a function.

Code analysis name: NEED_VIRTUAL_DTOR

Example

namespace no_destructor
{
    struct base {
        virtual void foo() {} // C26436, see remarks to understand the placement of the warning.
    };
}

The warning doesn't appear when the base class has either a virtual public destructor or a protected non-virtual destructor.

namespace virtual_destructor
{
    struct base {
        virtual ~base();
        virtual void foo() {}
    };
}
namespace protected_destructor
{
    struct base {
        virtual void foo() {}
    protected:
        ~base() {}
    };
}