﻿# V1114\. Suspicious use of type conversion operator when working with COM interfaces\. Consider using the 'QueryInterface' member function\.

The analyzer has detected a suspicious use of the type conversion operator when working with COM interfaces\.

Such usage can lead to several issues, including:

* The reference counter is not incremented\.
* Conversion to an incompatible type or interface may occur—for example, in cases involving multiple inheritance or changes to an interface version\.
* ABI compatibility issues\.

The correct way to work with COM interfaces is to use the '[QueryInterface](https://learn.microsoft.com/en-us/windows/win32/api/unknwn/nf-unknwn-iunknown-queryinterface(refiid_void))' function, which is specifically [designed](https://learn.microsoft.com/en-us/windows/win32/com/queryinterface--navigating-in-an-object) for this purpose\. This is because COM is a programming language\-independent technology, allowing COM objects to be implemented in languages other than C\+\+ and to reside in address spaces separate from that of the calling process\.

The 'QueryInterface' function [should](https://learn.microsoft.com/en-us/windows/win32/com/rules-for-implementing-queryinterface):

* check that the requested interface is accessible;
* return a pointer to the requested interface;
* increment the object reference counter\.

Here is a synthetic example of the error: the code includes COM interfaces, 'IDraw' and 'IShape', which handle a certain geometric shape:

```cpp
interface IDraw : public IUnknown
{
  ....
  virtual HRESULT Draw() = 0;
  ....
};

interface IShape : public IUnknown
{
  ....
  virtual HRESULT GetArea(double *area) = 0;
  ....
};
```

There is also the 'Circle' COM object that implements the 'IDraw' and 'IShape' interfaces:

```cpp
class Circle : public IDraw, public IShape
{
  ....
};
```

Look at an example of the incorrect COM object handling via the 'IDraw' interface:

```cpp
void foo(IDraw *ptrIDraw)
{
  IShape *ptrIShape = dynamic_cast<IShape*>(ptrIDraw);
  ....
  if (ptrIShape) 
    ptrIShape->GetArea(area);
  ....
}
```

In the above example, the reference counter for the 'Circle' object is not incremented\. To increment and decrement the counter, call the '[AddRef](https://learn.microsoft.com/en-us/windows/win32/api/unknwn/nf-unknwn-iunknown-addref)' and '[Release](https://learn.microsoft.com/en-us/windows/win32/api/unknwn/nf-unknwn-iunknown-release)' functions respectively\. Thus, using the 'QueryInterface' function is recommended, as it automatically handles the reference counting mechanism\.

Here is the fixed code:

```cpp
void foo(IDraw *ptrIDraw)
{
  IShape *ptrIShape = nullptr;
  ....
  if (SUCCEEDED(ptrIDraw->QueryInterface(IID_IShape, &ptrIShape))
  ....
}
```