-1

why we cannot intialize with vector size in class in c++?

#include <bits/stdc++.h>

using namespace std;

class s{
    public:
       vector<int> arr(4);
};
int main()
{
    cout<<"Hello World";
    int n = 10;
    std::vector<int> arr(n);

    return 0;
}

in this code i have intialize arr with 4 size but it showing error

we can intialize vector with size but why we cannot intialize

why it showing error:

main.cpp:15:24: error: expected identifier before numeric constant
   15 |        vector<int> arr(4);
      |                        ^
main.cpp:15:24: error: expected ‘,’ or ‘...’ before numeric constant
  • 5
    As default initializer list, try with `vector arr{4};` or `vector arr = vector(4);`. – songyuanyao Jun 08 '23 at 07:25
  • 4
    Side notes: (1) [#include ](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) (2) [using namespace std](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – wohlstad Jun 08 '23 at 07:26
  • 1
    Initializing the size should be done in the constructor initializer list. – πάντα ῥεῖ Jun 08 '23 at 07:26
  • The reason is you can only have `brace-or-equal-initializers` in your class/struct declaration. You are trying to use a constructor – Pepijn Kramer Jun 08 '23 at 07:32
  • For historical reasons (i.e. C), everything that has the form `Type name(parameters)` and is inside a class definition is a member function declaration. – molbdnilo Jun 08 '23 at 07:38
  • @πάνταῥεῖ I wouldn't consider the use of default initializers for member variables/implicitly generated&defaulted default constructors bad practice in any way. Following your advice would make the use of those impossible in many circumstances. – fabian Jun 08 '23 at 07:43

1 Answers1

0

C++ treats your "initialization" as a declaration of a function called arr and returning a vector<int>, so it expects a parameter declarator instead of 4.

clang gives a better(?) error message(using godbolt):

<source>:7:24: error: expected parameter declarator
       vector<int> arr(4);
                       ^

Solution: Use {} instead of (). Use assignment if you want a vector of 4 items, or use {} if you want a vector with a single 4.

x6dec3fb8
  • 81
  • 4
  • 1
    Unfortunately using `{4}` gives you a vector with a single element (value 4), not a vector of size 4. – BoP Jun 08 '23 at 08:10