Elephant Parade, Part 2: new
and nullptr
A Better Elephant Parade
Using our new tools,
new
andnullptr
, we are ready to improve our parade!Here's the plan…
- We will set a maximum number of
Elephant
s. - We will create an array with that many null pointers.
- When the user asks for an
Elephant
, we will allocate one on the heap usingnew
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;
}
Let's walk through our code and see how much better it is now!
(When logged in, completion status appears here.)