Decomposition and
encapsulation.
The operator+= decomposes into two tasks: (1) what the operator does to TrainRoute and (2) how to append an int to distances:
1 2 3 4
|
void TrainRoute::operator+=(int distance)
{
// append distance to distances
}
| |
The latter (append to a collection) is separate, standalone task. Unrelated to the operator+=.
How does one append to a collection? That can be several lines of code (as already shown).
It is better to have it in separate function(s), because those can be reused.
Enter the
std::vector
. Somebody has already written (and verified) the append logic for it.
1 2
|
std::vector<int> distances;
distances.push_back( 42 ); // append 42 to distances
| |
There is more to it. The vector does not encapsulate just a collection of integers and code to append more integers. It also keeps track of how many integers the collection has.
distances.size()
When you have an array, you need to keep track of how many elements it has.
On your train route you talk about "stops" and how many of them there are.
Can you calculate the number of stops from the number of distances?
If yes, then you don't need to keep track of stops, because you can get that from number of distances, which you must keep track of.
What are you supposed to learn from this homework?
* Is it about the
interface of a class?
* Is it about dynamic memory management?
* Both? Why? Each of the two topics above are plenty by themselves