38

So I was just browsing the source code of a library when I encountered this.

Font::Font(const sf::Font& font) :
        m_font{std::make_shared<sf::Font>(font)}
    {
    }

I don't understand the syntax

m_font{..}

What is it? What does it do. I am sorry if this is really stupid question. I don't know what to Google, so asking here.

isanae
  • 3,253
  • 1
  • 22
  • 47
Sidhin S Thomas
  • 875
  • 1
  • 8
  • 19
  • 4
    try googling: initializer list braces – Shloim Dec 18 '16 at 19:44
  • Are you asking about the initializer brace list, or are you asking about the make_shared? Google shared pointers if the latter. – mock_blatt Dec 18 '16 at 19:45
  • Here: http://stackoverflow.com/questions/24953658/what-are-the-differences-between-c-like-constructor-and-uniform-initialization – Ynon Dec 18 '16 at 19:47

3 Answers3

25

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.

  • 18
    This begs the question: Why would you use braces instead of parenthesis for initialization? – Délisson Junio Dec 19 '16 at 01:14
  • 6
    @wingleader See [this question](http://stackoverflow.com/questions/24953658/what-are-the-differences-between-c-like-constructor-and-uniform-initialization). – Blackhole Dec 19 '16 at 01:20
  • And what would one put in the curly braces after initializing the variables? – xuiqzy May 22 '20 at 18:49
9

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.

tambre
  • 4,625
  • 4
  • 42
  • 55
7

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.

Mo Abdul-Hameed
  • 6,030
  • 2
  • 23
  • 36