Last Comment Bug 230021 - XPCOM QueryInterface appears to be implemented wrongly in Weblock tutorial
: XPCOM QueryInterface appears to be implemented wrongly in Weblock tutorial
Product: Developer Documentation
Classification: Other
Component: General (show other bugs)
: unspecified
: x86 Linux
-- normal (vote)
: ---
Assigned To: Dawn Endico
: James Cox
Depends on:
  Show dependency treegraph
Reported: 2004-01-04 03:11 PST by Chris
Modified: 2012-12-28 15:53 PST (History)
2 users (show)
See Also:
QA Whiteboard:
Iteration: ---
Points: ---


Description User image Chris 2004-01-04 03:11:05 PST
User-Agent:       Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.4.1) Gecko/20031114
Build Identifier: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.4.1) Gecko/20031114

The weblock tutorial at 
gives the following code as an example of how to implement a QueryInterface

class Sample: public nsISupports
    nsrefcnt mRefCnt;

    virtual ~Sample();

    NS_IMETHOD QueryInterface(const nsIID &aIID, void **aResult);
    NS_IMETHOD_(nsrefcnt) AddRef(void);
    NS_IMETHOD_(nsrefcnt) Release(void);




NS_IMETHODIMP Sample::QueryInterface(const nsIID &aIID,
                     void **aResult)
    if (aResult == NULL)
        return NS_ERROR_NULL_POINTER;

    *aResult = NULL;

    if (aIID.Equals(kISupportsIID))
        *aResult = (void *) this;

    if (aResult != NULL)
        return NS_ERROR_NO_INTERFACE;

    return NS_OK;

NS_IMETHODIMP_(nsrefcnt) Sample::AddRef()
    return ++mRefCnt;

NS_IMETHODIMP_(nsrefcnt) Sample::Release()
    if (--mRefCnt == 0)
        delete this;
        return 0;

    return mRefCnt;

I'm a bit confused about the code in QueryInterface:

    if (aResult != NULL)
        return NS_ERROR_NO_INTERFACE;

Shouldn't aResult contain a reference to an interface? Why isn't this
code something like "if (aResult == NULL)" ??

Why does this function test that aResult is NOT equal to NULL? If the result is
a non-NULL value, wouldn't this mean that aResult has accessed an interface?

Somewhat confused.

Incidently, the XPCOM reference implementation of QueryInterface at might be a better way to go in the
tutorial. From what I can see, aIID is tested via the equals function, and if it
can't be found they place the zero into a temporary nsISupports pointer called
foundInterface, if it is found then the address of the interface is placed into
this variable. They then test the ptr with the following:

    nsresult status;
    if ( !foundInterface )
      status = NS_NOINTERFACE;
        status = NS_OK;

Reproducible: Always

Steps to Reproduce:
Documentation issue.

Note You need to log in before you can comment on or make changes to this bug.