-1

If I have a class

class Foo
{
public:
    Foo();
    Foo(int bar);

private:
    int m_bar;
}

What is the difference between these two ways to initialize it's member

Foo::Foo(int bar):
    m_bar(bar)
{

}

Foo::Foo(int bar):
    m_bar{ bar }
{

}

I was told on a code review to use Uniform Initialization Syntax, i.e. brace initialization. Is there a difference in this case? Or is it just a style preference?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Clay Brooks
  • 182
  • 1
  • 11

1 Answers1

2

In case of simple types, like int in your case, there is no difference. However, initialization of std::vector from STL will be completely different

std::vector<int> v1(3,1); // v1 consists of: 1, 1, 1
std::vector<int> v2{3,1}; // v2 consists of: 3, 1

Have a look at this answer if you want to see why generally brace {} initialization is better, however quoting from Scott Meyer's book Effective Modern C++, which I highly recommend:

[...] So why isn’t this Item entitled something like “Prefer braced initialization syntax”? The drawback to braced initialization is the sometimes-surprising behavior that accompanies it. [...]

Kamil Kuczaj
  • 193
  • 1
  • 8