Search code examples
c++inheritancevirtual-destructor

What happens when virtual destructors are declared, but have no implementation?


In C++ we can perfectly declare a function in a header file without actually implementing it. This compiles fine and usually this doesn't provide any problems, however... I am wondering if it can cause a problem when a virtual destructor is not implemented.

When a virtual destructor is not implemented and, when in that case we delete the instance of derived class through a pointer of a base class, will the destructor of the derived class still be called?

E.g.

class Base{
public:
    virtual ~Base() {}
};

class Derived: public Base {
public:
    ~Derived(); // HAS NO IMPLEMENTATION
};

Base *b = new Derived();
delete b;

NB: AS POINTED OUT IN THE COMMENTS,THE ABOVE EXAMPLE DOES NOT LINK CORRECTLY. It is provided here to explain a situation in which I'm trying to gain more insight, however in practice during the linking process, this example will result in an undefined reference to Derived error.


Solution

  • What happens when virtual destructors are declared, but have no implementation?

    If the destructor is ever called (such as in your example), the program violates the one definition rule, and is therefore ill-formed. No diagnostic is required by the standard, and a compiler will not be able to tell that there is anything wrong. But luckily you'll probably be saved by a linker error.

    In C++ we can perfectly declare a function in a header file without actually implementing it.

    This is true. But we cannot call such functions.


    The virtual and destructor are not very relevant to the question. These rules apply to all functions.