SDL2 + OpenGL access violation

  access-violation, c++, opengl, sdl-2

This works fine:

int main(int argc, char** argv)
{
    SDL_Init(SDL_INIT_VIDEO);

    SDL_Window* window = SDL_CreateWindow("Game", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 
SCR_WIDTH, SCR_HEIGHT, SDL_WINDOW_OPENGL);

    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 6);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);

    SDL_GLContext mainContext = SDL_GL_CreateContext(window);

    gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress);

    SDL_Event event;
    int running = 1;

    unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER);

    ...

    return 0;
}

But if I wrap the initialization into a class I get an access violation when I call glCreateShader even though I’m not getting any error messages when initializing SDL and OpenGL:

int main(int argc, char** argv)
{
    WindowManager wm;
    if (!wm.Construct())
        return 0;

    SDL_Event event;
    int running = 1;

    unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER); //<---- access violation here

    ...        

    return 0;
}

Here is my WindowManager class with the relevant functions:

class WindowManager
{
public:
    WindowManager() = default;
    
    bool Construct()
    {
        if (SDL_Init(SDL_INIT_VIDEO) < 0);
            return false;

        mWindow = SDL_CreateWindow("Game", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, 
        height, SDL_WINDOW_OPENGL);

        SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 6);
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);

        mContext = SDL_GL_CreateContext(mWindow);

        if (!mWindow)
        {
             spdlog::error("WindowManager could not be created!");

             return false;
        }

        if (!gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress))
        {
            spdlog::error("Failed to initialize GLAD!");

            return false;
        }

        return true;
    }

    SDL_Window* mWindow;
    SDL_GLContext mContext;
};

If anyone could some shine some light on what the issue could be I would greatly appreciate it!

Source: Windows Questions C++

LEAVE A COMMENT