SFML community forums

Help => Window => Topic started by: Sphynxinator on February 13, 2018, 07:24:51 pm

Title: isOpen() returns false and window shuts down immediately.
Post by: Sphynxinator on February 13, 2018, 07:24:51 pm
Hi all. I'm new to the SFML and the forum and I had some issues today. First of all, I want to use classes with SFML and I made a framework for this. File Structure is like this:

>main.cpp
>Framework>Window>Window.h and Window.cpp

Framework and main.cpp are at the same level. Window class lies beneath the framework folder.

main.cpp:
#include "Framework\Window\Window.h"
#include <iostream>
#include <SFML/Graphics.hpp>

int main()
{
        Window window(640, 360, "Title", false);

        while (window.IsOpen()) {
                window.Clear();
                window.Draw();
        }

    return 0;
}

 

Window.h
#ifndef WINDOW_H
#define WINDOW_H

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

class Window {
public:
        Window(int width, int height, std::string title, bool fullscreen);
        bool IsOpen();
        void Clear();
        void Draw();
private:
        sf::RenderWindow* window;
        int windowWidth;
        int windowHeight;
        std::string windowTitle;
        bool windowFullscreen;
};

#endif
 

Window.cpp
#include "Window.h"

Window::Window(int width, int height, std::string title, bool fullscreen) {
        windowWidth = width;
        windowHeight = height;
        windowTitle = title;
        windowFullscreen = fullscreen;

        window = &sf::RenderWindow(sf::VideoMode(windowWidth, windowHeight), windowTitle, sf::Style::Close | sf::Style::Titlebar);

        window->setFramerateLimit(60);
}

bool Window::IsOpen() {
        return window->isOpen();
}

void Window::Clear() {
        window->clear();
}

void Window::Draw() {
        window->display();
}
 

What is the problem. Does SFML supports object oriented programming? By the way, clear function gives access violation error in the code.

Thanks.
Title: Re: isOpen() returns false and window shuts down immediately.
Post by: eXpl0it3r on February 13, 2018, 07:45:10 pm
You're take the address of a temporary object (RenderWindow). As soon as you leave the constructor the object is destroyed and any use of the point results in undefined behavior.
Title: Re: isOpen() returns false and window shuts down immediately.
Post by: Sphynxinator on February 13, 2018, 07:58:00 pm
Thank you so much. What should I do? I don't want to use new keyword because of memory leakage. Using of new keyword is mandatory?
Title: Re: isOpen() returns false and window shuts down immediately.
Post by: eXpl0it3r on February 13, 2018, 08:02:48 pm
No, just use it as normal variable instead of pointer and use the initialization list or the create function.
Title: Re: isOpen() returns false and window shuts down immediately.
Post by: Sphynxinator on February 13, 2018, 08:09:07 pm
Thank you. It works now!!!  ;D