/* testArrayOfPointers.cpp John Sterling CS1124 What if we have a class with no default constructor? How can we create an array of objects? */ #include #include using namespace std; // Here is a simple Person class. // It defines a constructor that takes two arguments, but no // default constructor. Note that default constructors are provided // automatically, but only when no other constructor is provided. class Person { public: Person(const string& fn, const string& ln) : first(fn), last(ln) {} void display() const {cout << first << ' ' << last << endl;} private: string first, last; }; int main() { // We wish to have an array of people so we try: Person arrOfPeople[10]; // COMPILATION ERROR // There wasn't any Person default constructor, so this // didn't work. // Second approach is an array of pointers to people. Person* arrOfPeoplePtr[10]; // This works! // Initialize the pointers to NULL. for (int i = 0; i < 10; i++) arrOfPeoplePtr[i] = NULL; // But we would really like to use a dynamic array, because we may // need to resize later. // Third approach is a dynamic array of people. Person* dynamicArrayOfPeople = new Person[10]; // COMPILATION ERROR // This fails to work, for the same reason as the first appproach. // Fourth approach is a dynamic array of pointers to people. // How do we declare such a beast? Person** dynamicArrayOfPeoplePtr = new Person*[10]; // Initialize the entries to NULL. for (int i = 0; i < 10; i++) dynamicArrayOfPeoplePtr[i] = NULL; // Put one item into the array. dynamicArrayOfPeoplePtr[0] = new Person("Marilyn", "Monroe"); // Display it. dynamicArrayOfPeoplePtr[0]->display(); // Finally we want to free up all the people that have been // allocated for this array and the array itself. If we only // delete the array, then we will have a memory leak, all those // people we created on the heap. // So first we loop through the array deleting everyone. // Note that some of the entries in the array are still NULL // but that's ok, because deleting a NULL pointer doesn't do // anything. for (int i = 0; i < 10; i++) delete dynamicArrayOfPeoplePtr[i]; // Finally we can delete the array itself. delete [] dynamicArrayOfPeoplePtr; // It might be good to set the array pointer to NULL. dynamicArrayOfPeoplePtr = NULL; }