Search code examples
c++c++11sfmlgame-development

Whats this way of implementing a method in c++?


I want to create a game class using C++ SFML library. I try to use OOP style of coding and I was confused about a code I found on my learning book which is like this:

#include <SFML/Graphics.hpp>


class Game
{
public:
    Game();
    void run();

private:
    void proccessEvent();
    void update();
    void render();

private:
    sf::RenderWindow mWindow;
    sf::RectangleShape rect;

};

Game::Game()
: mWindow(sf::VideoMode(640, 480), "SFML Application") , rect()
{
    rect.setSize(sf::Vector2<float>(100.0f,100.0f));
    rect.setFillColor(sf::Color::Red);
}

I dont understand what's going on in the Game::Game part. Can someone please explain to me whats the : in that part??


Solution

  • It is called member initialiser list. See : https://en.cppreference.com/w/cpp/language/constructor

    By default, data members of classes are initialized before object itself. The same constructor implementation can be defined like this :

    Game::Game()
    {
        mWindow = RenderWindow(sf::VideoMode(640, 480), "SFML Application");
        rect = RectangleShape();
        rect.setSize(sf::Vector2<float>(100.0f,100.0f));
        rect.setFillColor(sf::Color::Red);
    }
    

    but this time, mWindow and rect will be initialized first with their default constructors and then during construction of game object their copy assignment operators are called to assign their values.

    If you use member initializer list, their constructor is called once. This will be more effective.