Search code examples
c++g++abstract-classclang++virtual-destructor

Virtual destructor for pure abstract base classes


I have seen here and here that a good rule of thumb is to use virtual destructors for every class that is intended as a base class. I have a pure abstract base class (only contains pure virtual functions and no data members; intended to be used as an interface).

class A {
    public:
        virtual void foo() = 0;
};

Is it possible to add a virtual destructor to this class without creating an implementation file (this class is defined in a header file included in several .cpp files) just for an empty destructor while also avoiding clang and g++ warnings such as -Wweak-vtables? I cannot put the empty definition in the header file with the pure abstract class because I will get multiple definitions of the destructor.


Solution

  • Whereas, clang generates warning for:

    class A {
    public:
        virtual ~A() {}
        virtual void foo() = 0;
    };
    

    using = default doesn't trigger it.

    class A {
    public:
        virtual ~A() = default;
        virtual void foo() = 0;
    };
    

    Even if both are valid.

    Demo