-3
#include <iostream>
#include <vector>

int main() {
    std::vector<int> v1(10);
    std::vector<int> v2{10};

    for (int x : v1)
        std::cout << x << ", ";

    std::cout << std::endl;

    for (int x : v2)
        std::cout << x << ", ";
}

makes

0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
10, 

How can C++ distinguish between () and {} when initialising a class?

And how can I create a constructor for both () and {} with different meanings?

Pascal K
  • 128
  • 1
  • 10
  • 6
    They're different characters. You'll need to be more specific. – sweenish Sep 30 '21 at 19:46
  • 1
    `{}` is using an initialization list, so it actually initializes the vector with those values. `()` is just providing an initial size of the vector, in this case 10 ints, all initialized to 0. – h0r53 Sep 30 '21 at 19:47
  • 3
    The `{}` constructor has `std::initializer_list` as parameter. As this example proves, you should never initialize standard containers with `{}`, use either `()` or `= {}` (if the vector had some other element type (not constructible from `int`), `vec{10}` would've filled it with 10 elements). – HolyBlackCat Sep 30 '21 at 19:47
  • This is a duplicate, I believe. https://stackoverflow.com/questions/47366453/direct-initialization-vs-direct-list-initialization-c – Drew Dormann Sep 30 '21 at 19:48
  • 1
    Some fun and informative viewing: [The Nightmare of Initialization in C++](https://www.youtube.com/watch?v=7DTlWPgX6zs) – user4581301 Sep 30 '21 at 19:49

1 Answers1

2

How can C++ distinguish between () and {} when initialising a class?

Because they are using different syntaxes, so the compiler can parse them differently and behave accordingly.

how can I create a constructor for both () and {} with different meanings?

Define 2 constructors, making one of them take a std::initializer_list as a parameter. {} will call that constructor. () will call the other one.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 1
    Can you overload `{}` to take some other parameter, or is it hard coded to `std::initializer_list`? – thc Sep 30 '21 at 19:53
  • `{}` itself (ie, a *braced-init-list*) has no type, so you can't overload on it. But it can be used to initialize an `initializer_list` object, which you can overload on. – Remy Lebeau Sep 30 '21 at 20:01