CodeQL documentation

Non-virtual destructor in base class

ID: cpp/virtual-destructor
Kind: problem
Severity: warning
Precision: high
   - reliability
   - readability
   - language-features
Query suites:
   - cpp-security-and-quality.qls

Click to see the query in the CodeQL repository

This rule finds classes with virtual functions but no virtual destructor. Deleting a class without a virtual destructor will only call the destructor of the type of the pointer being deleted. This can cause a defect if the pointer type is a base type while the object instance is a derived type.


Make sure that all classes with virtual functions also have a virtual destructor, especially if other classes derive from them.


class Base {
	Resource *p;
	Base() {
		p = createResource();
	virtual void f() { //has virtual function
	~Base() { //wrong: is non-virtual

class Derived: public Base {
	Resource *dp;
	Derived() {
		dp = createResource2();
	~Derived() {

int f() {
	Base *b = new Derived(); //creates resources for both Base::p and Derived::dp

	//will only call Base::~Base(), leaking the resource dp.
	//Change both destructors to virtual to ensure they are both called.
	delete b;