Search code examples
c++-cli

(How) Can I implement a method called Dispose in C++.CLI


I have an interface, not IDisposable, that has a method void Dispose(). I want to implement this interface in C++/CLI. It appears I can't. I have tried

    virtual void Finish() = IThing::Dispose 
    {}

but that gives a number of errors:

1>...: error C2039: 'Dispose': is not a member of '...IThing'
1>...: error C3653: 'Dispose': cannot be used as a named override: a function being overridden not found; did you forget to name the function explicitly, using a:: operator?
1>...: error C3766: 'MyNamespace::MyClass' must provide an implementation for the interface method 'void ...IThing::Dispose(void)'

(anonymised). C2039 and C3766 seem entertainlingly contradictory...

Am I missing something or is this plain impossible?

While I accept it was a bad design decision, changing the interface is not an option, it is implemented by hundreds of library classes.


Solution

  • Dispose is a reserved word, and can't be used in an explicit override. The best answer is to un-ask the question and change the interface. However,

    IF you can't change the interface

    AND the semantics of the interface's Dispose are sufficently close to IDispose::Dispose's

    AND you can put up with all the dispose-pattern side effects it will bring,

    THEN declaring a destructor for your class will create a method called Dispose that will satisfy your interface.