Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the weird syntax with curly braces in a constructor initializer list

Tags:

c++

This is described on cppreference, but in a somewhat hard to read format:

The body of a function definition of any constructor, before the opening brace of the compound statement, may include the member initializer list, whose syntax is the colon character :, followed by the comma-separated list of one or more member-initializers, each of which has the following syntax

...

class-or-identifier brace-init-list (2) (since C++11)

...

2) Initializes the base or member named by class-or-identifier using list-initialization (which becomes value-initialization if the list is empty and aggregate-initialization when initializing an aggregate)

What this is trying to say is that X::X(...) : some_member{some_expressions} { ... } causes the some_member class member to be initialised from some_expressions. Given

struct X {
    Y y;
    X() : y{3} {}
};

the data member y will be initialised the exact same way a local variable Y y{3}; would be initialised.

In your case, std::make_shared<sf::Font>(font) produces the value that will be used to initialise the m_font class member.


That is a list initialization aka brace initializer list. More specifically, in this case it's a direct-list initialization.

Basically the m_font variable is initialized with the value that's given in the curly braces, in this case it's initialized to a shared_ptr for the font object that's given to the constructor.


The class Font has a member called m_font of type std::shared_ptr<sf::Font>, so in the constructor of the class Font that member is being initialized with a shared pointer to font.