H
He Shiming
Hi,
I'm having a little bit of trouble regarding pointer casting in my program.
I don't understand why the following two cases produce different results.
Case 1:
IInterface *pInterface = new CImplementation();
pInterface->Method();
Case 2:
void* pInterface = static_cast<void*>(new CImplementation());
static_cast<IInterface*>(pInterface)->Method();
In these two cases, "IInterface" is an interface definition class, it
contains no member variables, only public pure virtual methods are defined.
"CImplementation" is derived from IInterface, and it implements those pure
virtual methods.
Now, if CImplementation is derived only from IInterface, the above two cases
will work the exact same way. However, when CImplementation derives from
other classes, which also contain virtual or pure virtual methods, Case 2
will fail. It'll cause a crash mainly because the ->Method() call isn't
actually calling IInterface::Method(), depending on the actual
inheritance, ->Method() may be pointed at a pure virtual method of another
class. Case 1 still works. Why is that? And more importantly, why is the
above two cases work differently?
Thanks,
I'm having a little bit of trouble regarding pointer casting in my program.
I don't understand why the following two cases produce different results.
Case 1:
IInterface *pInterface = new CImplementation();
pInterface->Method();
Case 2:
void* pInterface = static_cast<void*>(new CImplementation());
static_cast<IInterface*>(pInterface)->Method();
In these two cases, "IInterface" is an interface definition class, it
contains no member variables, only public pure virtual methods are defined.
"CImplementation" is derived from IInterface, and it implements those pure
virtual methods.
Now, if CImplementation is derived only from IInterface, the above two cases
will work the exact same way. However, when CImplementation derives from
other classes, which also contain virtual or pure virtual methods, Case 2
will fail. It'll cause a crash mainly because the ->Method() call isn't
actually calling IInterface::Method(), depending on the actual
inheritance, ->Method() may be pointed at a pure virtual method of another
class. Case 1 still works. Why is that? And more importantly, why is the
above two cases work differently?
Thanks,