Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Window init problem  (Read 3303 times)

0 Members and 1 Guest are viewing this topic.

M.S.T.O.P.

  • Newbie
  • *
  • Posts: 2
    • View Profile
Window init problem
« on: July 24, 2010, 05:43:44 am »
I'm trying to initialize a window (win) in the constructor of an class (Program), but the window closes as soon as the the constructor finishes, preventing the main loop (mainLoop) from running.  There are no compiler errors, and I'm using SFML 1.6 with Visual Studio C++ 2008 Express.  My code is shown below:

Code: [Select]
// program.h
//--------------

#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>

class Program
{

public:

sf::Window* win;

Program(unsigned int w, unsigned int h, unsigned int bitdepth, char* title);
void mainLoop();
void eventHandler();
void drawScreen();
~Program();
};


//program.cpp
//--------------

#include "program.h"

Program::Program(unsigned int w, unsigned int h, unsigned int bitdepth, char* title)
{
   // Create window
win = &sf::Window(sf::VideoMode(w, h, bitdepth), title);
}

void Program::mainLoop()
{
while (win->IsOpened())
    {
eventHandler();
drawScreen();
}
}

void Program::eventHandler()
{
sf::Event Event;

    while (win->GetEvent(Event))
    {
        if (Event.Type == sf::Event::Closed)
            win->Close();

        if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Escape))
            win->Close();
    }
}

void Program::drawScreen()
{
win->Display();
}

Program::~Program()
{}



//main.cpp
//----------

#include "program.h"

int main()
{
    Program p(800, 600, 32, "Test");
p.mainLoop();

    return 1;
}

dunce

  • Jr. Member
  • **
  • Posts: 77
    • View Profile
Window init problem
« Reply #1 on: July 24, 2010, 07:34:42 am »
1. Have a look at tutorials how to create a render window. If you want to create a window in the heap use
Code: [Select]
sf::RenderWindow* win = new sf::RenderWindow();
....
....
delete win;

2. You should create a RenderWindow object instead of Window one, as Window does not have Draw method at all and you won't be able to render game objects.

Laurent

  • Administrator
  • Hero Member
  • *****
  • Posts: 32498
    • View Profile
    • SFML's website
    • Email
Window init problem
« Reply #2 on: July 24, 2010, 10:35:01 am »
Here you take the address of a local variable that will be destroyed as soon as the constructor ends.

So:
- don't use a pointer
- use the initialization list to call your windows's constructor, or use its Create function

Code: [Select]
class Program
{
public:

    Program(...args...) : window(args)
    {
    }

private:

    sf::Window window;
};
Laurent Gomila - SFML developer

M.S.T.O.P.

  • Newbie
  • *
  • Posts: 2
    • View Profile
Window init problem
« Reply #3 on: July 26, 2010, 10:36:06 pm »
OK, I have it working now.  Thanks for the help.  :)