Search code examples
c++functionreferencesfmlencapsulation

Using reference variables or send them as function parameters


I have the next class:

class State {
public:
    State(StateMachine& machine, sf::RenderWindow& window)
        : mMachine   { machine }
        , mWindow    { window } { }

    void draw();
protected:
    StateMachine&     mMachine;
    sf::RenderWindow& mWindow;

    std::vector<std::unique_ptr<Scene>> m_scenes;   
};

In the draw function I iterate the vector m_scenes and call the function drawScene(), but the Scene class need a sf::RenderWindow in order to draw.

Should I send the mWindow when creating a new Scene?

class Scene {
public:
    Scene(sf::RenderWindow& window)
        : mWindow    { window } { }

    void drawScene() {
        mWindow.draw(...);
    }
protected:
    sf::RenderWindow& mWindow;
};

Or it would be better to send the mWindow as a paramater?

class Scene {
public:
    Scene() {}

    void drawScene(sf::RenderWindow& window) {
        window.draw(...);
    }
};

Or should I create a getter in the class State and send a reference for the State class?

class State {
public:
    State(...);

    sf::RenderWindow& getWindow() { return mWindow; }
};

class Scene {
public:
    Scene(State& state)
        : mState { state } {}

    void drawScene() {
        mState.getWindow().draw(...);
    }
protected:
    State& mState;
};

And if I'm using a getter, will it slow down the code?


Solution

  • It depends on what your intention is. If you want to draw on a single window that you know when the scene is created, you may use the passing to constructor variant. If you want to draw a scene on multiple/different windows, or you don't know the window yet at scene creation, pass the window reference to drawScene. The getter seems a little overkill but it won't slow down your code.

    Considering what code you presented, I would pass the window reference when drawing, it seems useless to put references to the window in each scene.