So here's a C++ exercise on dynamic memory allocation and objects creation. Basically - a custom class Student and a custom class Group which keeps an array of pointers to Students inside. There's obviously a problem in Group's destructor but I've spent hours reading manuals and surfing forums and still cannot understand what I'm doing wrong.
Any comments are welcome.
UPD: the problem is - error on exit. "Debug assertion failed... _BLOCK_TYPE_IS_VALID..."
class Student{
char *firstName;
char *lastName;
public:
Student(): firstName(NULL), lastName(NULL){}
Student(const char *fname, const char *lname){
firstName = new char[32];
lastName = new char[32];
strcpy_s(firstName, 32, fname);
strcpy_s(lastName, 32, lname);
}
void Show(){
cout << firstName << " " << lastName << endl;
}
~Student(){
if(lastName != NULL)
delete[] lastName;
if(firstName != NULL)
delete[] firstName;
}
};
class Group{
Student *students;
int studentCounter;
public:
Group(){
students = NULL;
}
Group(const int size){
students = new Student[size];
studentCounter = 0;
}
void Push(Student *student){
students[studentCounter] = *student;
studentCounter++;
}
void ShowAll(){
for(int i = 0; i < studentCounter; i++){
students[i].Show();
}
}
~Group(){
if(students != NULL)
delete[] students; //problem here?
}
};
void main(){
Student jane("Jane", "Doe");
Student john("John", "Smith");
Group group(2);
group.Push(&jane);
group.Push(&john);
group.ShowAll();
_getch();
}