Chemistpp
Chemistpp

Reputation: 2056

Execute class code once C++

I am trying to use sdl as a window manager for openGL. I looked into using Windows native API, but looked to confusing.

With that being said, I have a class Window which I would like to wrap all the SDL stuff in for my windows management right now. Figure it will let me swap out windows management later if I find I do not want to use SDL.

I am guessing that a lot of openGL initialization code only needs to be run one time.

    if(SDL_Init(SDL_INIT_EVERYTHING) < 0 ) { 
        exit(0x1);
    }

    SDL_GL_SetAttribute(SDL_GL_RED_SIZE,           8);
    SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE,         8);
    SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE,          8);
    SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE,         8);

    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE,        16);
    SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE,       32);

    SDL_GL_SetAttribute(SDL_GL_ACCUM_RED_SIZE,     8);
    SDL_GL_SetAttribute(SDL_GL_ACCUM_GREEN_SIZE,   8);
    SDL_GL_SetAttribute(SDL_GL_ACCUM_BLUE_SIZE,    8);
    SDL_GL_SetAttribute(SDL_GL_ACCUM_ALPHA_SIZE,   8);

    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 2);

Then in the class constructor I can create the window with

Window::Window(int winW, int winH) {

    if((Surf_Display = SDL_SetVideoMode(winW,winH,32, SDL_HWSURFACE | SDL_GL_DOUBLEBUFFER | SDL_OPENGL | SDL_RESIZABLE )) == NULL) {
        exit(2);
    }

    glClearColor(0, 0, 0, 0);
    glClearDepth(1.0f);

    glViewport(0, 0, winW, winH);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    glOrtho(0, winW, winH, 0, 1, -1);

    glMatrixMode(GL_MODELVIEW);
    glEnable (GL_BLEND); 

    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    glLoadIdentity();


}

I'm just not sure how to go about doing this. If I put the code before I define the class in the header, does this achieve the desired result?

;init code
;class window { };

Upvotes: 0

Views: 72

Answers (1)

Daniel Jour
Daniel Jour

Reputation: 16156

The simplest thing would be to put that initialisation code into a function and the to just call this function from main:

/* header */
void init_window_management (void);    
/* some source file */
void init_window_management (void) {
  // your code
}    
/* main file */
// ... also include that header ...
int main(int argc, char ** argv) {
  // ...
  init_window_management();
  // ... use instances of the window class
}

Then there's also std::call_once.

If I put the code before I define the class in the header, does this achieve the desired result?

No. A header is for function and class declarations. Code to execute lives in (member) functions, these are then called (ultimately) via the main function.

Upvotes: 1

Related Questions