Why do I need another set of braces after brace-initializing a member variable?

356 Views Asked by At

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.

3

There are 3 best solutions below

2
avakar On BEST ANSWER

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?

0
Mike Seymour On

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

6
TemplateRex On

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.