-2

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??

Ethan
  • 301
  • 1
  • 5
  • 19
  • 1
    https://en.cppreference.com/w/cpp/language/constructor – Jarod42 Aug 02 '20 at 17:05
  • 4
    It's an initializer list. It's used to initialize members of the class. This is basic C++, covered early on in any C++ book, but it surprising how many newbies have never seen it. I guess people don't read C++ books. – john Aug 02 '20 at 17:05
  • 1
    You really should start to read a good c++ book first, to learn the basics of the language, before looking for online tutorials, or writing code without understanding the basic concepts of the language. Without that basic knowledge you are not able to determine if the tutorial shows is correct, and you might draw the wrong conclusions. StackOverflow (and most other online platforms and tutorials) is no alternative to a good book. – t.niese Aug 02 '20 at 17:15

1 Answers1

2

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.

Muhammet Ali Asan
  • 1,486
  • 22
  • 39
  • 1
    That's not accurate. A constructor is called only once, in your alternative code above it's the *assignment operators* that are called to assign values to the members. – john Aug 02 '20 at 17:07
  • @john To be extra accurate, there are two `RenderWindow` constructors called. The Default Constructor and whichever constructor `RenderWindow(sf::VideoMode(640, 480), "SFML Application");` uses. Then, the second instance is move assigned to `mWindow`. – François Andrieux Aug 02 '20 at 17:09
  • True but the constructors of the types of the members are still called twice in this instance. – Jupiter Aug 02 '20 at 17:14