Usually, books usually discourage the use of conversion operators when wrapping up c structs. For example the c++ string, which is (believed to be) a wrapper of a C char array, does not provide a conversion operator. Instead it gives the the method c_str().
However, I seriously think my case may be an exception. I am wrapping up an SDL_Surface. Here’s the class declaration.
/** Wraps up SDL_Surface **/
class surface
{
SDL_Surface* _surf;
public:
/** calls SDL_LockSurface().
** throws surface_lock_exception on failure.
**/
void lock();
/** calls SDL_UnlockSurface() **/
void unlock();
/** calls SDL_LoadBMP().
** throws image_load_exception on failure.
**/
void load_bmp(const string&);
/** calls SDL_FreeSurface(). **/
void free();
/** destructor. Also free()s the internal SDL_Surface. **/
~surface();
};
In this case, I seriously think I should add a conversion operator to SDL_Surface* for easy compatibility with other SDL Functions that require an SDL_Surface*.
What do you think:
- Would a conversion operator be prudent?
- Or Should I use a method like
c_str()? - Or is there another, better solution?
Although providing a conversion operator would be required to pass your new-fangled wrapper class to existing SDL library functions, you must ask yourself if you really need to.
The reason that
c_str()exists at all is so that us C++ programmers can usestd::stringand then call all those archaic runtime library functions that never heard of it. If you’re writing a C++ program from the ground up, would any of your function calls take aconst char*? No, they’d take aconst std::string&, perhaps.So, if you are wrapping up SDL in a nice library, then one must ask if you should ever be exposing the underlying data structures. Surely your library will always want to talk to a
Surfaceand not care what is going on underneath?So my preferred solution would be to hide it away and let those classes that deal with working with the underlying SDL library, do so.