Reputation: 289
I am trying to implement a simple Instructor List which is a dynamic array of dynamic"Instructor" objects. First of all I am not allowed to use STL neither the vector etc. The goal is start a dynamic instructor array on heap with a default value, and when need to add instructor, expand the arraysize if necessary. The problem is initializing the array of instructors with a default size is not possible because the Instructor object's size is dynamic also. Is there a nice way to handle this?
Here is the Instructor class
class Instructor{
private:
string title, firstName, lastName, telNo, roomNo, userName, eMail;
string courses[];
public:
Instructor();
Instructor(string, string, string, string, string, string, string, string);
string getTitle();
string getFirstName();
string getLastName();
string getTelNo();
string getRoomNo();
string getUserName();
string getEMail();
string getCourse(int courseIndex);
void setTitle(string);
void setFirstName(string);
void setLastName(string);
void setTelNo(string);
void setRoomNo(string);
void setUserName(string);
void setEMail(string);
void setCourse(string);
void print();
};
The part that i try to initialize the array:
int size = 5;
Instructor *instructorList;
instructorList = new Instructor[size];
It throws the error: Type containing an unknown size array is not allowed
Upvotes: 1
Views: 125
Reputation: 79
Create a simple example similar to your code. It works fine.
class A {
private:
char *field;
public:
A() {};
A(char *field) : field(field) { }
char *getField() const {
return field;
}
};
int main() {
int size = 5;
A *aList = new A[size];
for (int i = 0; i < size; i++) {
aList[i] = A((char *) std::to_string(i).c_str());
std::cout << aList[i].getField();
}
return 0;
}
Use it to fix your error
Upvotes: 0
Reputation: 75062
Use a pointer to store (the address of) the array.
Instead of
string courses[];
use
string *courses;
and initialize it like
courses = new string[size_of_elements];
To expand the number of elements, you will have to
courses
Upvotes: 3