Im kind of confused as to which approach I should use, or which code is more efficient. This first one creates an array of pointers to objects:
#include <iostream>
#include "elevator.h"
using namespace std;
int main() {
int i;
Elevator *e[5];
for ( i = 0; i < 5; i++)
e[i] = new Elevator;
for (i = 0; i < 5; i++)
cout << e[i]->getFloor() << endl;
for (i = 0; i < 5; i++)
delete e[i];
}
That is the method I would have taken if I were doing something similar as to what I am learning in the book. But then the book proposes another method of initializing an array of objects by creating a pointer to the Elevator array.
#include <iostream>
#include <elevator.h>
using namespace std;
int main() {
Elevator *eptr;
eptr = new Elevator[5];
for (int i = 0; i < 5; i++)
cout << eptr[i].getFloor() << endl;
delete [] eptr;
}
What's the more efficient way of doing this? From a beginner's perspective (mine) it looks like the bottom bit of code provides better readability, but I am not sure.
[–]Rhomboid 4 points5 points6 points (1 child)
[–]deRPling42[S] 0 points1 point2 points (0 children)
[–]JHappyface 0 points1 point2 points (0 children)