Search code examples
c++windowscomcalling-convention

Should I mention calling conventions in pure virtual functions?


Here is an example, IUnknown interface from Unknown.h in Windows SDK:

  • In C++:
IUnknown {
    public:
        virtual HRESULT STDMETHODCALLTYPE QueryInterface( 
                REFIID riid,
                void** ppvObject) = 0;
        //AddRef
        //Release
};
  • In C:
typedef struct IUnknownVtbl {
    HRESULT (STDMETHODCALLTYPE *QueryInterface)(
        IUnknown* This,
        REFIID riid,
        void **ppvObject);
    //AddRef
    //Release
} IUnknownVtbl;

interface IUnknown {
    CONST_VTBL IUnknownVtbl* lpVtbl;
};

You can see STDMETHODCALLTYPE before the virtual functions which is __stdcall (generally). So, my question, is it important to mention calling conventions in pure virtual functions? Or calling conventions is managed internally in virtual functions by compiler or compiler options (e.g. /Gz for __stdcall)?

Also when I don't mention any calling conventions before virtual functions in source code (or with any compiler option), executable works fine.


Solution

  • You need to specify them. The fact that you are calling the function via (essentially) a function pointer makes no difference - the caller and the function called still need to agree on things like the order in which the parameters are passed.

    But why do you need to specify them in the base class?

    Well firstly I would expect the compiler to complain if you didn't, and secondly you might be calling said functions via an object or (more likely) pointer to an object of said base class, in which case the declarations in the base class are all the compiler has to go on.