Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Templates are nice for similar algorithms of different data types. Say I make a

ID: 655580 • Letter: T

Question

Templates are nice for similar algorithms of different data types. Say I make a template stack of a basic data type...

Stack<int> stck(10);
stck.Push(5);
I'd pop it...

int x = stck.Pop();
x would be 5. If I call pop again, there are no items, so I have the method just return 0 for null. It could be something else, but whatever.

But now, if I change the template type to a compound variable (a structure type - say, RECT), and the stack is empty, it can't return 0. It expects a RECT type, but I don't have any left. How do I make this work for basic data types and compound variables? Exceptions?

Explanation / Answer

3 options

make popping en emtpy stack undefined and don't worry about it

throw an exception

return default constructed T() (which happens to be 0 for the numeric types)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote