A Reference Implementation of QueryInterface

by Scott Collins

last modified 3 May 1999

Abstract: The right way to write QueryInterface().

Document Status: Draft. More explanation needed.

The Implementation

NS_IMETHODIMP
nsMyImplementation::QueryInterface( REFNSIID aIID, void** aInstancePtr )
  {
    if ( !aInstancePtr )
      return NS_ERROR_NULL_POINTER;

    if ( aIID.Equals(nsIX::GetIID()) )
      *aInstancePtr = NS_STATIC_CAST(nsIX*, this);
    else if ( aIID.Equals(nsIY::GetIID()) )
      *aInstancePtr = NS_STATIC_CAST(nsIY*, this);

    // ...as many cases as needed...

    else if ( aIID.Equals(kISupportsIID) )
      *aInstancePtr = NS_STATIC_CAST(nsISupports*, NS_STATIC_CAST(nsIX*, this));
    else
      *aInstancePtr = 0;


    nsresult status;
    if ( !*aInstancePtr )
      status = NS_NOINTERFACE;
    else
      {
        NS_ADDREF( NS_REINTERPRET_CAST(nsISupports*, *aInstancePtr) );
        status = NS_OK;
      }

    return status;
  }

What's So Good About It?


Valid HTML 4.0! CSS Copyright© 1999 by Netscape; use is subject to the NPL.