Search code examples
c++type-conversionsdloperator-keyword

C++ How can I degrade a class instance in a function call without explicitly casting?


I want to make a Window class that manages a SDL_Window pointer and where accessing the SDL_Window pointer for function calling is as easy and just using the Window class instance and having a conversion operator act as a "getter". Like this:

Window win("some name",10,10,100,100,Flags);
SDL_DoSthWithWin(win,10.0f); //SDL_DoSthWithWin uses SDL_Window* but its converted.

My current attempt looks (somewhat) like this:

class Window{
private:
    //Irrelevant
    SDL_Window *window; //SDL Type for handling Windows. Always a pointer
    static Window *ActiveWindow //Pointer to the active Window.
    //More irrelevant stuff
public:
    static Window& getActive(); //this returns a reference to the active obj
    Window(someParms);
    explicit operator SDL_Window* (){return this->window;}; //This conversion operator should do the trick?
    //More irrelevant stuff really
}

However, the outcome is that for some reason it doesnt work without having to explicitly cast like so:

SDL_DoSthWithWin((SDL_Window*)win,---);

This would be nice if only the entire point of making that conversion operator was to save the letters it would take to write ".getWindow()"

Well how can I (properly) do this so that I dont have to cast.


Solution

  • Well you do say that the conversion operator is explicit. That means you actually have to be explicit about that conversion.

    I should add that this is usually a bad choice, having an implicit conversion operator like that. Having to be explicit and use a getWindow (or similarly named function) to get the SDL_Window pointer makes the code easier to understand, read and maintain.