Tolga Şen
Tolga Şen

Reputation: 289

Dynamic Arrays Of Dynamic Objects

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

Answers (2)

Sergey Morzhov
Sergey Morzhov

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

MikeCAT
MikeCAT

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

  1. Allocate new array with new size
  2. Copy contents of old array to the new array
  3. Destroy only the old array (do not destroy the new array here!)
  4. Assign the address of the new array to courses

Upvotes: 3

Related Questions