Noskol Noskol - 2 months ago 8
C++ Question

Passing SDL_Window to another class

I am trying to pass SLD_Window *window to another class to work on it.
I don't know if it is a proper way of programming, but I would like to try that.
I am creating a SDL_Window *Window in main.cpp and then passing the pointer *Window to another class.
I found out that all Renderer functions doesn't have any impact in window, but when I copied them to window.cpp screen was red.
Looks like I pass the pointer but it creates completly new window.
How can I work in many classes on same window which is defined in main class?
It is like this because I would like to build a Draw.cpp where I would keep all drawing functions.

main.cpp

SDL_Window *WindowMain = NULL;
window Window(WindowMain , name);
renderer = SDL_CreateRenderer(WindowMain , -1, SDL_RENDERER_ACCELERATED);
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 100);
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer)


window.h

class window {
public:
window(SDL_Window *Window, const char* Nazwa );
virtual ~window();
private:
SDL_Window *okno;
};


window.cpp

window::window(SDL_Window *Window, const char* Nazwa) {
okno = Window;
if(SDL_Init(SDL_INIT_VIDEO) !=0)
{
printf("Unable to initialize SDL due error: %s", SDL_GetError());
}
okno = SDL_CreateWindow(Nazwa,
SDL_WINDOWPOS_CENTERED, // X position
SDL_WINDOWPOS_CENTERED, // Y position
800, // Width
600, // Height
SDL_WINDOW_SHOWN);
if(okno == NULL){
printf("Unable to create window due error: %s", SDL_GetError());
}
}

window::~window() {
SDL_DestroyWindow(okno);
SDL_Quit();
}

Answer

the main routine declares okno locally:

SDL_Window *okno = NULL;
window Window(okno, name);   // `okno` is NULL and remains NULL
renderer = SDL_CreateRenderer(okno, -1, SDL_RENDERER_ACCELERATED);

in window.cpp you're using a member called okno, a global, whatever, but that cannot be the same variable.

window::window(SDL_Window *Window, const char* Nazwa) {
    okno = Window;
    if(SDL_Init(SDL_INIT_VIDEO) !=0)
    {
        printf("Unable to initialize SDL due error: %s", SDL_GetError());
    }
    okno =  SDL_CreateWindow(Nazwa,

both okno variables have a total different scope and you cannot initialize okno from the window constructor like this.

=> okno remains NULL at main level => your SDL_CreateRenderer is passed a NULL window pointer.

(Not to mention the design is really wierd,so is the naming...)

What you probably want is:

window Window(name);
SDL_Window *okno = Window.okno;
renderer = SDL_CreateRenderer(okno, -1, SDL_RENDERER_ACCELERATED);
Comments