Search code examples
c++sfml

Window not opening in SFML


Basically, I am making a pong clone in c++ and sfml, and I'm using classes, which I have very little knowledge on. The problem is, I'm first of all trying to open the window and clear it in black. The files compile without errors, and run without errors, but the window just doesn't appear.

I believe it has something to do with the constructor, but again, I'm not sure. I looked at all the other questions to see if any answer my question and none of them have given me an answer. Ignore the other header files, they aren't doing anything at the moment.

game.hpp

class Game
{
public:
  Game();
  void run();
public:
  sf::RenderWindow window;
private:
  void processEvents();
  void update();
  void draw();
};

pong.cpp

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

#include "game.hpp"
#include "players.hpp"
#include "ball.hpp"

Game::Game() {
 sf::RenderWindow window(sf::VideoMode(640, 480), "Game Window", sf::Style::Default);
 window.setFramerateLimit(60);
}
void Game::processEvents() {
  sf::Event event;
  while (window.pollEvent(event)) {
    if (event.type == sf::Event::Closed) {
      window.close();
    }
  }
}
void Game::draw() {
  window.clear(sf::Color::Black);
  window.display();
}
void Game::run() {
  while (window.isOpen()) {
    processEvents();
    draw();
  }
}
int main(int argc, char const *argv[]) {
  Game game;
  game.run();
  return 0;
}

The window is meant to open and be black, but when the program is run, it runs fine, but the window doesn't pop up. I've been looking at it for a few hours now, have asked some people on a discord server but can't find an answer.


Solution

  • In your Game constructor, you are creating a local window object, that is immediately destroyed when the constructor ends.

    Instead of this:

    Game::Game() {
     sf::RenderWindow window(sf::VideoMode(640, 480), "Game Window", sf::Style::Default);
     window.setFramerateLimit(60);
    }
    

    Do this:

    Game::Game() : window(sf::VideoMode(640, 480), "Game Window", sf::Style::Default)
    {
     window.setFramerateLimit(60);
    }
    

    in order to initialise the window data member with a non-default initialisation.