I am new to C++ and have a question for everyone. I want to create a bunch of different object classes. For example, if I had an object called student, where each student has a name and id. The id is also the name of the object of student. So if I wanted to make 10 new students, where each student had an id of 1 to 10, how would I do that? Ideally, I'd like to do something like:
for(int i = 0; i < 10; i++){
Student i;
}
6.setName(fwhofdih);
But obviously that doesn't work. Its clear I'm new to all this. Any ideas on how I can do this? Thanks!
You would put instances of the Student class into the vector. Like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
vector<Student*> studpoints;
studpoints.push_back(new Student(constructor));
//dont forget to delete your newly allocated space the following function will do what you need, thank
//http://stackoverflow.com/questions/891913/c-stdvector-of-pointers-deletion-and-segmentation-faultstemplate <class C> void FreeClear( C & cntr ) {
for ( typename C::iterator it = cntr.begin();
it != cntr.end(); ++it ) {
delete * it;
}
cntr.clear();
}
note: this is using pointers to students not student objects.
class Student
{
private:
int id;
... //other fields
public:
Student(int sid) {
id = sid; //assign the id in the constructor
}
//create a method to get the student's id since the id field is private (hidden outside this class)
int getID() {
return id;
}
... //other methods
};
//main function
int main() {
Student roster[10]; //make a place to hold your students
for( int id = 0; id < 10; id++ )
roster[id] = Student(id); //create a Student with id id and store it into the roster at index id
... //do stuff with roster
}