Okay so I have a class Student
, which takes a number and a vector as a parameter for the constructor. Everything works well, until I output the values of the vector for every instance. The problem is that the same vector is being shared with EVERY instance I create, but I want it to be unique for every single one!
//Student.h
#ifndef __Grade_calculator__Student__
#define __Grade_calculator__Student__
#include <iostream>
#include <vector>
using namespace std;
class Student {
private:
string name;
int score;
int class_count;
int test_count;
vector <Student> students;
vector <int> Scores;
public:
Student();
Student(string n,vector<int> &s);
~Student();
int getScore(){return score;}
void display_specific_transcript(int student);
void display_all_transcript();
void set_students();
void transcript();
void calculator();
};
#endif /* defined(__Grade_calculator__Student__) */
//Student.cpp
#include "Student.h"
#include <vector>
Student::Student(){ //initialize all vairables
//cout << "student created!\n";
name = "";
for(int i = 0; i< Scores.size();i++)
{
Scores[i] = 0;
}
}
Student::Student(string n, vector<int> &s) {
//set variables equal to parameters
//cout << "Student created with different constructor\n";
name = n;
/*for(int i = 0; i< s.size();i++)
{
//Scores[i] = s[i];
cout << s[i] << "from cin\n";
//cout << Scores[i] << "from new vector\n";
}*/
Scores = s;
cout << s.size();
}
Student::~Student() {
//cout << "Student destroyed";
}
void Student::calculator()//MAIN PROGRAM
{
this->set_students();//Enter students information
this->display_all_transcript();//Displays everyones transcript
}
void Student::set_students()
{
cout << "Enter the number of students in the class ";
cin >> class_count;
cout << "Enter the number of tests given during this course ";
cin >> test_count;
for (int i = 0; i < class_count; ++i)//goes through students in class
{
cout << "\nEnter student " << i+1 << " name: ";
cin >> name;
for(int j = 0; j < test_count; j++)
{
cout << "For test " << j+1;
cout << ", Enter student " << j+1 << " score: ";
cin >> score;
Scores.push_back(score);
}
Student s(name,Scores);
students.push_back(s);
}
}
void Student::display_all_transcript()
{
for (vector <Student>::iterator iter = students.begin(); iter != students.end(); iter++)
{
if(iter->name != "") iter->transcript();
else cout << "Error! Student doesn't exist\n";
}
}
void Student::transcript()
{
cout << "\n******"<< name << "'s Transcript******\n";
int i = 1;
for (vector <int>::iterator iter = Scores.begin(); iter != Scores.end(); iter++)
{
cout << "Test score "<< i << ": " << *iter << endl;
i++;
}//HERE IS THE PROBLEM!!!
/*
If you test the input, you will see that for the first student everything is okay,
and the vector displays only its scores, but if there is more than one,
every other student will have their scores ADDED to the same vector!
*/
}
//Main.cpp
#include <iostream>
#include "Student.h"
int main()
{
Student student;
student.calculator();
return 0;
}