Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we use "virtual inheritance" in COM?

Tags:

c++

com

I have read some vague statement that virtual inheritance doesn't provide the memory structure required by COM, so we have to use the normal inheritance. Virtual inheritance is invented to handle the diamond problem.

Could someone show me an illustration of the difference of memory structure details between this two inherit approaches? And the key reason why virtual inheritance is not suitable for COM. A picture would be best.

Many thanks.

like image 956
smwikipedia Avatar asked Jun 21 '10 02:06

smwikipedia


1 Answers

First, in COM the behavior of virtual inheritance is always used. QueryInterface can't return a different value for e.g. the IUnknown base pointer depending on what derived class was used to obtain it.

But you're correct that this isn't the same mechanism as virtual inheritance in C++. C++ doesn't use a QueryInterface function to upcast, so it needs another way of getting the base class pointer.

The memory layout issue is caused because COM requires that all methods of a base interface can be called directly using a derived interface pointer. AddRef is a good example. In COM, you can call AddRef and pass any derived interface as the this pointer. In C++, the AddRef implementation would expect the this pointer to be of type IUnknown* const. The difference is that in C++, the caller finds the base pointer, while in COM the callee does the adjustment to find the base pointer, so each derived interface needs a distinct implementation (of QueryInterface, at least) aware of the offset from the derived interface pointer passed in to the base pointer.

At first glance, a C++ compiler could choose, as an implementation detail, to have the callee perform the adjustment just like COM. But the pointer-to-member-function rules aren't compatible with this implementation of virtual base classes.

like image 100
Ben Voigt Avatar answered Nov 16 '22 23:11

Ben Voigt