Hello. I am currently learning about stacks in C++ and I was wondering why I was recommended to return values by reference, instead of returning a value by a string. Can you explain why it's recommended? Thank you!
top() returns a reference to the topmost element in the stack. If you didn't use & when defining test you would create a new string object that is a copy of the string that top() returns a reference to. Creating a copy is extra work, especially if the string is long, so that is why you make it a reference.
Note that since test is a reference to an element in the stack you need to be careful not using it after the element has been removed from the stack. Switching the order of line 18 and 19 would be a mistake for this reason.