1

I've been flipping through the SFML blueprints book to start getting my feet wet in graphics. I noticed in one of their code examples in their game class constructor:

Game::Game() : _window(sf::VideoMode(800,600), "SFML Title") {
     code code code...
}

The _window(sf::VideoMode(800,600), "SFML Title") being placed before the {}, not inside. Is this bad practice? What is doing this called? I'm still new to c++ but I haven't come across something like this yet.

Danh
  • 5,916
  • 7
  • 30
  • 45
Gim
  • 19
  • 1
  • 2
    It's good practice, it's called [member initializer lists](http://en.cppreference.com/w/cpp/language/initializer_list) – Danh Nov 08 '16 at 03:49

2 Answers2

2

Is this bad practice?

No, it's good practice. If the member is const qualified type or reference type, it's the only way to initialize that member in constructor.

What is doing this called?

It's called member initializer lists

Danh
  • 5,916
  • 7
  • 30
  • 45
1

That's called a member initialization list. They're part of the C++ language. A member initialization list allows you to initialize members during class initialization. One reason why they're good practice is because they allow you to initialize const members when assigning won't work. For example, the following class definition won't work because const int member1 wasn't initialized with a value, nor can you assign to a const int because const makes it read-only.

class Game{
private:
    const int member_var; //won't work, needs to be initialized
    int member_var2;
public:
    Game() {} //Game constructor
}; 

With initialization lists, you're able to initialize const members like these and other variables by adding a colon after your constructor definition (but before the brackets to define it) and initializing members as needed, either with direct initialization (using "()") or uniform initialization (using "{}"). To initialize multiple members, separate them with a comma.

class Game{
private:
    const int member_var; 
    int member_var2;
public:
    Game(): member_var(1), member_var2(2) {} 
    //Uniform initialization is ": member_var{1}, member_var{2}" 
};

In your example, the Game() constructor was defined outside the class definition (likely in another .cpp file) via Game::Game() with a member initialization list. I'm guessing _window is a class with one constructor that takes sf::VideoMode(800,600) and "SFML Title" as arguments.

DragonautX
  • 860
  • 1
  • 12
  • 22