Coming from a Java background, following code is confusing me. Confusion here is C++ object creation without new keyword. I am creating this object Student_info info; and then adding it to a vector. Since I am not creating it using new keyword, will it be allocated on stack and be destroyed after the loop exits? If that is the case, how the last loop is able to extract the info from vector correctly? Shouldn't it throw exception as all the object added to the vector has been destroyed?
struct Student_info {
string name;
vector<double> marks;
};
int main()
{
int num = 2;
vector<Student_info> student_infos;
for (int i = 0; i < 3; i++) {
Student_info info; //will this object be destroyed once this loop exits?
cout << "Enter name:";
cin >> info.name;
double x;
cout << "Enter 2 marks";
for (int j = 0; j < num; j++) {
cin >> x;
info.marks.push_back(x);
}
student_infos.push_back(info);
}
for (int i = 0; i < 3; i++) {
cout << student_infos[i].name;
for (int j = 0; j < num; j++) {
cout << student_infos[i].marks[j];
}
cout << endl;
}
return 0;
}
newkeyword.