Original Post
I have been reading "C++ for Game Programmers" for the past couple of weeks. I enjoy the book, but there is a code example that has me stumped and ashamed that I don't really understand what the author is trying to say. Let me give you an example. If you happen to have the book, the pages are 264 – 267. What has me ashamed to call myself a programmer is the next passage?
class IRenderable
{
public:
bool Render( ) = 0;
// …
};
class GameEntPhysical : public GameEntity,
public IRenderable
{
public:
bool Render( ) ;
// …
};
void * GameEntPhysical::QueryInterface( Interface interface ) const
{
if (interface == IRENDERABLE)
{
IRenderable * pRender = static_cast< IRenderable * >(this);
return (void *)(pRender);
}
return NULL;
};
// ...
void * pInterface = obj.QueryInterface(IRENDERABLE);
if (pInterface)
{
IRenderable * pRender = static_cast< IRenderable * >(pInterface);
}
// ...
Quote:I'm not quite fallowing the logic here by when the author says, "Without it, the returned value could not be safely cast to the correct interface type." How does taking the static_cast, which should be a different location in memory, and returning that interfaces location through the use of a void * "most likely change the actual value of the pointer?" Shouldn't returning just pRender or the void * of pRender be the same thing? How is it possible for the cast to change the value of the pointer? Thanks for the help and insight.
Notice that we first cast the this pointer to the type of pointer we want, and then we return it as a plain void pointer. Even though it looks like an unnecessary step, that casting will most likely change the actual value of the pointer. Without it, the returned value could not be safely cast to the correct interface type.