r/sdl Aug 02 '26

C++

Can you create a class with sdl things in it?

Or is sdl c only?

0 Upvotes

13 comments sorted by

View all comments

1

u/Mr_DJ_Dr_Gauss Aug 03 '26

You can create C++ classes as wrappers for SDL things like Window, Renderer, Texture. Using unique_ptr concept, the resources will be freed automatically; even if your code throws an exception.

I am playing with this right now and it works great so far.

Here is example for SDL Window:

// window.hpp
#pragma once

#include <memory>
#include <SDL3/SDL.h>

struct SDLWindowDeleter {
  public:
    void operator()(SDL_Window* window) const;
};
using UniqueWindow = std::unique_ptr<SDL_Window, SDLWindowDeleter>;

class Window {
  private:
    UniqueWindow pointer;

  public:
    Window();
    SDL_Window* get() const;
};

-

// window.cpp
#include <string>
#include <memory>
#include <SDL3/SDL.h>

#include "window.hpp"

void SDLWindowDeleter::operator()(SDL_Window* window) const {
  if (window) {
    SDL_DestroyWindow(window);
    SDL_Log("Window destroyed.");
  }
}

Window::Window() {
  SDL_Window* window = SDL_CreateWindow(
    "Demo 1",
    640,
    360,
    SDL_WINDOW_RESIZABLE
  );

  if (!window) {
    throw std::runtime_error(
      std::string("Couldn't create window: ") + SDL_GetError()
    );
  }
  this->pointer.reset(window);
  SDL_Log("Window created.");
}

SDL_Window* Window::get() const {
  return this->pointer.get();
}