CS 70

Elephant Parade, Part 2: new and nullptr

A Better Elephant Parade

  • LHS Cow speaking

    Using our new tools, new and nullptr, we are ready to improve our parade!

  • RHS Cow speaking

    Here's the plan…

  • We will set a maximum number of Elephants.
  • We will create an array with that many null pointers.
  • When the user asks for an Elephant, we will allocate one on the heap using new and set a pointer to point to it.

Here's the code (changes are highlighted).

int main() {
    constexpr size_t MAX_ELEPHANTS = 5;
    Elephant* elephants[MAX_ELEPHANTS];
    for (size_t i = 0; i < MAX_ELEPHANTS; ++i) {
        elephants[i] = nullptr;
    }

    string anotherElephant = "y";
    size_t numElephants = 0;
    while (anotherElephant == "y") {
        if (numElephants >= MAX_ELEPHANTS) {
            cout << "Sorry! We can't accept any more elephants!" << endl;
            anotherElephant = "n";
        } else {
            ++numElephants;
            cout << "Please enter elephant " << numElephants << endl;

            string name;
            cout << "Name: ";
            cin >> name;

            int age;
            cout << "Age: ";
            cin >> age;

            elephants[numElephants - 1] = new Elephant{name, age};

            cout << endl << "Another elephant (y/n)? ";
            cin >> anotherElephant;
            cout << endl;
        }
    }

    // We'll just assume this works
    sortElephantPtrsByName(elephants, elephants + MAX_ELEPHANTS);

    cout << "The elephants are parading!" << endl;

    for (size_t i = 0; i < numElephants; ++i) {
        // We changed from . to -> here
        cout << elephants[i]->getName() << " (" << elephants[i]->getAge() << ")" << endl;
    }

    return 0;
}
  • LHS Cow speaking

    Let's walk through our code and see how much better it is now!

Which of the following are advantages we gained by using the heap in this example?

(When logged in, completion status appears here.)