3

I was trying to use brace-initialization (which thankfully Visual Studio 2013 actually supports), but for some reason when I do it on a class, it requires two sets of braces. For example:

class NumberGrabber {
    int number;
public:
    NumberGrabber() : number{ 5 }{}

    int getNumber() { return number; }
};

Why does it require me to say number { 5 }{}? That doesn't really make visual sense to me.

TemplateRex
  • 69,038
  • 19
  • 164
  • 304
sircodesalot
  • 11,231
  • 8
  • 50
  • 83

3 Answers3

14

The former set of braces is the initializer for number, the latter is the compound statement that defines the body of the constructor. With proper formatting, this may become clearer.

NumberGrabber()
    : number{5}
{
}

Does that make more sense?

avakar
  • 32,009
  • 9
  • 68
  • 103
  • 1
    And equivalent to the C++03 way: `NumberGrabber() : number(5) {}` – gx_ Jul 24 '13 at 13:21
  • 1
    Ooooh, gah. This is sort of like the `runs to` operator (---->) http://stackoverflow.com/questions/1642028/what-is-the-name-of-this-operator . – sircodesalot Jul 24 '13 at 13:21
4

In C++11 you can also do

#include <iostream>

// look ma, no {}
class NumberGrabber {
    int number = 5;
public:
    int getNumber() { return number; }
};

int main()
{
    std::cout << NumberGrabber().getNumber() << "\n";    
}

Live example (works for clang and g++) that prints 5.

TemplateRex
  • 69,038
  • 19
  • 164
  • 304
  • 2013 actually does allow that. Thanks for the heads up. – sircodesalot Jul 24 '13 at 13:36
  • 1
    @sircodesalot it really starts paying of if you have many class data members and many single argument constructors, because then you only have to initialize the corresponding data member, and the others will be taken from the in-class initalizers. – TemplateRex Jul 24 '13 at 13:38
  • Yeah, having started with C#/Java, it surprised me that you *couldn't* do this in previous iterations of C++. – sircodesalot Jul 24 '13 at 13:44
  • @sircodesalot are you sure visual studio 2013 preview does ? I just tried and it's not happy with it. It says only static const integral members can be initialized like that (non c++11 behaviour, that is). – teh internets is made of catz Jul 25 '13 at 10:46
  • Oh, I take that back. You do get an error but only after you try to compile :/ – sircodesalot Jul 25 '13 at 13:12
  • 2
    @sircodesalot I found that it's going to be a feature of 2013 RTM, see http://blogs.msdn.com/b/vcblog/archive/2013/06/28/c-11-14-stl-features-fixes-and-breaking-changes-in-vs-2013.aspx – teh internets is made of catz Jul 26 '13 at 13:40
3

A constructor is a function, and a function definition needs a body. {} is an empty function body.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644