I'm a bit rusty on C++, haven't used it for a while. So I need to make a data structure that can hold objects and do operations with them. Just like a array list. Now I first create and init a dynamic array of my class type :
Student* array_of_students = new Student[SIZE];
Then I create a Student object, say like this :
Student student(param1, param2, etc..);
I also provide a destructor since I use a lot of char pointers (I know I should use string but this is for learning purpose only.) where I delete number of pointers that hold some names.
~Student(){ /* delete filed1; etc */ }
Well, when I try to list those names, I get some random values, probably because pointers are deleted, meaning destructor is called, and even if I have reference to a particular object with array_of_students
, those fields are destroyed and I don't have anything to display. This probably happens because Student
instance goes out of scope and calls it's destructor.
So what is the solution in here? How can I hold them as long as array_of_students
is alive?
I believe I need to define some sort of copy constructor that will copy that original student instance to a new copy
that will be referenced by array_of_students
. Your thoughts would be helpful.
EDIT :
class Student{
private :
char *_name;
public :
Student(){}
Student(char* name){
_name = new char[strlen(name)];
strcpy(_name, name); }
char* getNaziv(){return _name;}
~Student(){delete _name;}
};
int main()
{
Student* array_of_students = new Student[5];
char input[100];
for(int i = 0; i < 5; i++){
cout << "Input name : "<<endl;
cin >> input;
Student tmp(input);
array_of_students[i] = tmp;
}
for(int i = 0; i < 5; i++){
cout <<"Name is : "<< array_of_students[i].getNaziv()<< endl;
}
}