What's the use of casting a pointer to (Derived*) right before assigning it to a variable of type (Base*)?

Viewed 110

What's the use of the static_cast<IDropSource*> in this piece of code (taken from here):

HRESULT CDropSource::QueryInterface(REFIID riid, void **ppv){
    IUnknown *punk = NULL;
    if (riid == IID_IUnknown) {
        punk = static_cast<IUnknown*>(this);
    } else if (riid == IID_IDropSource) {
        punk = static_cast<IDropSource*>(this);
    }
    
    *ppv = punk;
    if (punk) {
        punk->AddRef();
        return S_OK;
    } else {
        return E_NOINTERFACE;
    }
}

I fail to see what's the purpose of casting this to IDropSource* if it's going to be assigned to a variable of type IUnknown*.

Does this make any difference when later calling punk->AddRef()?

0 Answers
Related