Search code examples
c++compilationlanguage-lawyerdestructorpure-virtual

Does compiler really enforce implementation of pure virtual destructor?


To validate the statement "compiler & linker enforce existence of function body for pure virtual destructor." from this geeksforgeeks article, I compiled this code:

class Base
{
public:
    virtual ~Base()=0; // Pure virtual destructor
};

class Derived : public Base
{
public:
    ~Derived()
    {
        std::cout << "~Derived() is executed";
    }
};

int main()
{
    //Derived d;   <<<
    return 0;
}

which compiled without any error. So why the compiler didn't chose to enforce the existence of the function body in this case?


Solution

  • Because the compiler (the entire translation process, actually) doesn't have to enforce anything if you perform an ODR1 violation. According to the C++ standard at [basic.def.odr/4]:

    Every program shall contain exactly one definition of every non-inline function or variable that is odr-used in that program; no diagnostic required. The definition can appear explicitly in the program, it can be found in the standard or a user-defined library, or (when appropriate) it is implicitly defined (see [class.ctor], [class.dtor] and [class.copy]). An inline function shall be defined in every translation unit in which it is odr-used.

    The compiler is perfectly within its right to figure out your program isn't actually using2 the destructor of Derived (and therefore the destructor of Base), and just not bother with notifying you.


    1 One Definition Rule
    2 What does it mean to “ODR-use” something?