So just as a back story to what I've done so far and what I want to achieve...
Currently I'm using a whole heap of singleton classes to pass my instances around which is going to become a very bad idea very soon as I'm looking into multithreading and have heard(more like read) that singletons can become evil and a huge problem when multithreading is involved.
In my main init class, I've got code that initialises an window, renderer and a surface (SDL2). I'm wanting to break the code down so that I've got a class that handles only the window code, same with the renderer and surface too.
I'm looking for ways (if they're possible) to make an instance of a variable which will hold say the primary window, and then be able to access said variable without using a dedicated function... e.g:
in the init function of window:
bool Window::init() {
m_primaryWindow = SDL_CreateWindow(creation info here);
if (!m_primaryWindow) {
SDL_LogInfo(INFO, "Primary Window Created");
return true;
}
else {
SDL_LogCritical(CRITICAL, "Could Not Create Primary Window:\n%s", SDL_GetError());
return false;
}
};
As you can see, normal right? Well, say I create a Window
class in Game
I'd have to add a function such as:
SDL_Window* primaryWindow = window.getPrimaryWindow();
To get that instance. But that's not what I want! I want to create only one SDL_Window
variable in Window
and reference to that in a function that uses a string maybe? eg:
SDL_Window* Window::getWindow(std::string id);
so that in Game
I could just init and show the window and then call the instance like:
Window m_window;
m_window.getWindow(primaryWindow);
so that I can use that instead of constantly creating SDL_Window* variables all over my code.
Same needs to be done with the renderer too!
EDIT:
Ok, so I've made the following changes and it works... but I can't access the values within the mapped structure:
Window.hpp
typedef struct {
SDL_Window* window;
const char* title;
int width;
int height;
int flags;
} m_windowStruct;
typedef std::map<std::string, m_windowStruct*> m_windowMap;
Window.cpp
bool Window::init() {
if (!createWindow("window creation variables here") {
return true;
}
else {
return false;
}
};
bool Window::createWindow(std::string id, const char* title, int width, int height, int flags) {
m_windowMap* windowMap;
m_windowStruct windowData;
windowData.window = SDL_CreateWindow(title,
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
width, height, flags);
if (!windowData.window) {
windowData.title = tile;
windowData.width = width;
windowData.height = height;
windowData.flags = flags;
windowMap->insert(m_windowMap::value_type(id, &windowData));
SDL_LogInfo(INFO, "Window creation successful");
return true;
}
else{
return false;
}
};
So I guess my question now is.. How would I grab the window
pointer from the struct within the map?
(also as a side note, how would I then destroy the pointer once I'm finished?)