1

Recently I study the book "Inside COM", and I find a code sample as below part: The Interface is defined as struct. The IX and IY inherit IUnknown. The CA class inherit IX and IY. As far as I know, in this case CA should have the two virtual point to the virtual functions, one belongs to IX and the other belongs to IY?

Interface IUnknown  
{
    virtual void QueryInterface() = 0;         
    virtual void AddRef() = 0  
    virtual void Release() = 0;  
};

Interface IX : IUnknown
{
     void X()
     {
        printf("X()\n");
     }
};

Interface IY : IUnknown
{
     void Y()
     {
        printf("Y()\n");
     }
};

class CA : public IX, public IY
{
    public:
    void QueryInterface()
    {
        printf("QueryInterface()\n");
    }

    void AddRef()   
    {
        printf("AddRef()\n");
    }

    void Release()
    {
        printf("Release()\n");
    }
};

My question is why CA only implements QueryInterface(), AddRef(), Release() and the code can work. Why isn't there the ambiguous problem that the implementation of QueryInterface(), AddRef(), Release() belongs to IX or belongs to IY.

thanks.

1
  • You should remove the c++/cli tag... Commented Jul 7, 2012 at 10:05

1 Answer 1

1

A function declared in a derived class will override any matching virtual functions declared in any base class. So, for example, CA::QueryInterface() will override the IUnknown::QueryInterface() accessible through both base class sub-objects.

You would get an ambiguity if both IX and IY were to override it, and CA didn't, and you tried to call it via a reference to CA. In that case, there are two potential overloads with no reason to prefer either. In detail:

Interface IX : IUnknown
{
     void QueryInterface() { /* do something */ }
};

Interface IY : IUnknown
{
     void QueryInterface() { /* do something else */ }
};

class CA : public IX, public IY 
{
    // inherits both IX::QueryInterface and IY::QueryInterface
};

CA c;
c.QueryInterface();     // ERROR: which QueryInterface is that?
c.IX::QueryInterface(); // OK: specified unambiguously
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks the answer. And would you please explain what "In that case, there are two potential overloads with no reason to prefer either" mean? thanks..
@Weber: I've added more detail about that. It's not really relevant to your question though; just an example of how ambiguities can occur in similar situations to yours.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.