Search code examples
c++vectorreferencecompiler-errorsnon-static

C++ Vectors with pre-determined size throwing compile errors


I am very new to C++ and trying to create a simple Student class with a vector of scores of type int.

Here's my class:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <fstream>
#include <sstream>

using namespace std;

class Student {
    string last;
    string first;
    vector<int> scores(10);

public:
    Student():last(""), first("") {}
    Student(string l, string f) {
        last = l;
        first = f;
    }
    ~Student() {
        last = "";
        first = "";
    }
    Student(Student& s) {
        last = s.last;
        first = s.first;
        scores = s.scores;
    }
    Student& operator = (Student& s) {
        last = s.last;
        first = s.first;
        scores = s.scores;
        return *this;
    }

    void addScore(int n) {
        scores.push_back(n);
    }
};

For some reason, I'm getting multiple reference to non-static member function must be called; did you mean to call it with no arguments in reference to the vector scores.

Here's my full list of errors:

main.cpp:15:22: error: expected parameter declarator
    vector<int> scores(10);
main.cpp:15:22: error: expected ')'
main.cpp:15:21: note: to match this '('
    vector<int> scores(10);
main.cpp:30:4: error: reference to non-static member function must be called; did you mean to call it with no arguments?
            scores = s.scores;
main.cpp:35:4: error: reference to non-static member function must be called; did you mean to call it with no arguments?
            scores = s.scores;
main.cpp:35:15: error: reference to non-static member function must be called; did you mean to call it with no arguments?
            scores = s.scores;
main.cpp:40:4: error: reference to non-static member function must be called; did you mean to call it with no arguments?
            scores.push_back(n);

I've tried many things but still have no idea where these errors are coming from. I'm very new to C++, so please forgive me. Any help would be appreciated.


Solution

  • You can't initialize a data member like this:

    vector<int> scores(10);
    

    You need one of these forms instead:

    vector<int> scores = vector<int>(10);
    vector<int> scores = vector<int>{10};
    vector<int> scores{vector<int>(10)};
    

    The reason is to avoid initializations that could look like function declarations. Note that this is syntactically valid:

    vector<int>{10};
    

    but it initializes the vector to have size 1, with a single element with value 10.