Search code examples
c++c++11com

Virtual destructor on IUknown Derived interfaces


I have been doing some code learning by reading some existing code. I know the importance of having a virtual destructors on Interfaces which are non com types. I mean which do not derive from IUnkown or IInspectable.

However, I am not able to understand why it is not required to have a virtual destructor on a COM interface.

I have my interface defined like this

MIDL_INTERFACE("0D70D782-809D-403B-AC95-XXXXXX")
IMyInterface : IUnknown
{
    public:
      virtual bool method1() = 0;
      virtual int method2() = 0;
}

And at the same time I have another interface which doesnt derive from IUnkown like this

    class ISampleLogic
    {
      public:
         virtual ~ISampleLogic() {};
         //some more methods

    }

Why there is no virtual destructor for first interface?

Thanks in advance


Solution

  • IUnknown has a method called Release(). Its job is to decrement the object's reference count and destroy the object if that reference count drops to zero. So it acts as the destructor; and an explicit destructor is therefore not required.

    If you have an IUnknown pointer (say IUnknown* punk), you shouldn't delete it, but call Release() instead (punk->Release()). That's because other processes may have a reference count on the object.

    It's down to the implementation of the interface to ensure that the entire object is deleted. That implementation may well contain classes with virtual destructors, if necessary.