Why in C++ I can't declare a dynamic array of objects with parmatetrized constructors?

Viewed 193

I try to make simple program that will display students names from array of objects called "Student", I know that it can be easily done using vectors but I would like to do that using dynamic array. My code:

class Student {
public:
  string name;
  Student(string name){
    this->name = name;
  }
};

void DisplayStudentsNames(Student array[],int length) {
  for(int i=0;i<length;i++){
    cout << array[i].name << endl;
  }
}

int main(int argc, char** argv) {
  Student ** array = new Student *[3];
  array[0] = new Student("Michael");
  array[1] = new Student("Tom");
  array[2] = new Student("Timmy");
  DisplayStudentsNames(*array,3);
  return 0;
}

I am not sure why it does not work, it does compile but program just "stops responding" after displaying first student name. I wonder what is the issue, I have read here that if Class does not have any zero argument constructor you cannot create an array of dynamic objects dynamically, I wonder why is that? I'm just assigining new objects to pointers (in C# that's the normal way creating a class).

1 Answers

Your issue is here

DisplayStudentsNames(*array,3);

What you are actually passing to DisplayStudentNames() here is the first element is the array array. The issue is that array[0] is not an array, it is a pointer to a single object. Therefore when you try and iterate it you get undefined behaviour, an exception would be the best case scienorio here (as you saw with your infinite loop).

You can fix this by changing

DisplayStudentsNames(*array,3);

to

DisplayStudentsNames(array,3);

and DisplayStudentsNames to take Student**

Also this wont work:

cout << array[i].name << endl;

Each element in array is a pointer to a Student object and in C++ accessing an object through a pointer requires using the -> operator (so array[i]->name instead).

Side note:

Student(string name){
    this->name = name;
  }

This is bad C++, use initaliser lists for setting members on creation instead, as it allows compiler optimisations and is easier to read

Related