Search code examples
c++interfacepure-virtual

Does C++ create default "Constructor/Destructor/Copy Constructor/Copy assignment operator" for pure virtual class?


Do C++ compilers generate the default functions like Constructor/Destructor/Copy-Constructor... for this "class"?

class IMyInterface
{
    virtual void MyInterfaceFunction() = 0;
}

I mean it is not possible to instantiate this "class", so i think no default functions are generated. Otherwise, people are saying you have to use a virtual destructor. Which means if i dont define the destructor virtual it will be default created, not virtual.

Furthermore i wannt to know if it is reasonable to define a virtual destructor for a pure virtual Interface, like the one above? (So no pointers or data is used in here, so nothing has to be destructed)

Thanks.


Solution

  • Furthermore i wannt to know if it is reasonable to define a virtual destructor for a pure virtual Interface, like the one above? (So no pointers or data is used in here, so nothing has to be destructed)

    It's not only reasonable, it's recommended. This is because in the case of virtual function hierarchies, (automatically) calling a destructor of a specialized class also calls all destructors of it's base classes. If they are not defined, you should get a linking error.

    If you define at least one virtual function in your class you should also define a virtual destructor.

    The destructor can be defined with =default though:

    Here's a corrected (compilable) code example:

    class ImyInterface
    {
        virtual void myInterfaceFunction() = 0;
        virtual ~ImyInterface() = 0;
    }
    
    ImyInterface::~ImyInterface() = default;