Search code examples
c++sfml

How to use a pollevent through out multiple class "Union variable" (sfml)


From my understanding how sf::Event works there could only be one a loop since they all share the same memory space so my question I would I able to use sf::Event throughout my other class with:

#include <SFML/Graphics.hpp>

int main()
{
    sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
    sf::CircleShape shape(100.f);
    shape.setFillColor(sf::Color::Green);

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear();
        window.draw(shape);
        window.display();
    }

    return 0;
 }

So would I just have reference my sf::Event or is this incorrect if I want to share it with my other classes

class a{

    void handleEvent(sf::Event& event){
        if (event.type == sf::Event::KeyPressed)
        {
            if (event.key.code == sf::Keyboard::Escape)
            {
                std::cout << "the escape key was pressed" << std::endl;
                std::cout << "control:" << event.key.control << std::endl;
                std::cout << "alt:" << event.key.alt << std::endl;
                std::cout << "shift:" << event.key.shift << std::endl;
                std::cout << "system:" << event.key.system << std::endl;
            }
        }
    }

};

Solution

  • sf::Event is implemented as a union of different events' data which means that only one of the data structures is active at the time and it depends on the value of the type field, but it's something that works per-instance not per-type.

    Hence you can safely pass events around and, if I understood you correctly, your code is fine in this situation.