valarray size?

I am confused regarding the definition of a valarray.
The constructor is listed as explicit valarray( std::size_t count );
So I assumed std::valarray<double> va(10); is a valid way of declaring an array.

The code declares a Student class, which takes an integer as one of the arguments and uses the integer, I assumed, in the same way as above.

However the warning message warning: narrowing conversion of ‘n’ from ‘int’ to ‘double’ inside { } [-Wnarrowing] appears

Can anybody suggest why the code below generates the warning messages?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <string>
#include <iostream>
#include <valarray>

typedef std::valarray<double> Scores;
    
class Student {
  private:
    std::string name;
    Scores scores;
    std::ostream & arr_out(std::ostream & os) const;
  public:
    Student() : name{"Anonymous"}, scores{} {}
    explicit Student(int n) : name{"Anonymous"}, scores{n} { }
    explicit Student(const std::string & s, int n) : name{s}, scores{n} { }
    explicit Student(const std::string & s, const double pd, int n) : name{s}, scores{pd, n} { }
    ~Student() {}
};

int main() {
  Scores sa(10); // this variable declaration is accepted
  Student s;
  return 0;
}
Last edited on
You should be using parentheses() instead of the braces{} in your initialization lists.

1
2
3
4
    Student() : name("Anonymous"), scores() {}
    explicit Student(int n) : name("Anonymous"), scores(n) { }
    explicit Student(const std::string & s, int n) : name(s), scores(n) { }
    explicit Student(const std::string & s, const double pd, int n) : name(s), scores(pd, n) { }



Topic archived. No new replies allowed.