123 456 789 0
123 456 789 0

Reputation: 10865

Vector C++ with your own Class

I tried searching in google but it just shows what I'm not looking for.

I have this class called Student and in my main class I instantiated it to be a vector.

I tried adding this line in my main class

vector<Student> students;
students[0].setFirstName("Test");

and it throws an error on my Student class

void Student::setFirstName(string fname) { firstName = fname; }

It says that EXC_BAD_ACCESS. I'm using Xcode in Macintosh

EDIT: I want it to be dynamic that's why I didn't specify the size.

Upvotes: 0

Views: 519

Answers (4)

Ken Wayne VanderLinde
Ken Wayne VanderLinde

Reputation: 19347

As I'm sure you know, the expression students[0] means that you are trying to access to first item in the vector. But in order to access the first item, you must first add a first item.

Quite simply, add a call to vector::push_back before trying to use anything in the vector. Alternatively, declare the vector by

vector<Student> students(/*number of default Students here*/);

There are also other ways, but just make sure you have what you're trying to use.

To be quite specific, the index you pass to the [] operation must satisfy the condition 0 <= index && index < students.size(). In your case, students.size() == 0, so 0 <= index && index < 0, which is clearly not possible to satisfy.

Upvotes: 5

iammilind
iammilind

Reputation: 70078

You are going out of range for your vector size. You are trying to access an element which doesn't exist. You can declare its size at initialization.

vector<Student> students(SIZE);

As a side note, the setter methods typically take const reference:

void Student::setFirstName(const string &fname) { firstName = fname; } 

Upvotes: 2

Benjamin Lindley
Benjamin Lindley

Reputation: 103741

When you create your vector, how many elements are in it? None. And yet you try to access an element right away. You need to put elements in it first. Either at initialization, like this:

vector<Student> students(10);

Or some other method, like push_back, or resize.

Upvotes: 5

ildjarn
ildjarn

Reputation: 62995

Your vector is empty, yet you try to access its first element. Try putting something in the vector before accessing its contents.

Upvotes: 2

Related Questions