Suppose I have a class that implements several interfaces
class CMyClass : public IInterface1, public IInterface2 { };
and in the member function of this class I need to get a void* pointer to one of these interfaces (a typical situation in IUnknown::QueryInterface() .
A typical solution is to use static_cast to achieve pointer adjustment:
void* pointer = static_cast<IInterface2*>( this );
and in this case, it is safe if there is no known class inherited from CMyClass . But if such a class exists:
class CDerivedClass : public CUnrelatedClass, public CMyClass {};
and I accidentally do
void* pointer = static_cast<CDerivedClass*>( this );
and this is actually a pointer to an instance of CMyClass , the compiler will not catch me, and the program may encounter undefined behavior later - static_cast becomes unsafe.
The proposed solution is to use an implicit conversion:
IInterface2* interfacePointer = this; void* pointer = interfacePointer;
It seems that this will solve both problems - pointer adjustment and the risk of an unacceptable downgrade.
Are there any problems in the second solution? What could be the prerequisites for the first?
source share