Thursday, March 08, 2007

C++ Quiz

What can you tell me about this code besides the fact that it frustrated this author?
class Foo
{
// ...
};

unsigned char *
bar()
{
// ...
}

int
main()
{
// ...
Foo * foo = (Foo *)bar();
// ...
}

1 comment:

Anonymous said...

First of all, it seems odd that you'd need to cast an unsigned char pointer to a class pointer. I'd ask myself why. Maybe the bar method should be a method on a factory class that returns a pointer to a base class. But, assuming the bar function can't be rewritten and you really do need to cast its return value into a pointer to a Foo object, I'd write the code this way:

Foo* foo = reinterpret_cast<Foo*>(bar());

I'd maybe add a comment explaining why this unusual cast is necessary. Another thing to consider -- who manages the memory returned by bar? I've seen many a memory leak over the years, so I'm always looking out for them.