December
1998 QUESTION 2 Total Marks: 20 Marks |
Click here to access other
questions
SUGGESTED SOLUTIONS
|
(a) | List three types of polymorphism found in C++. | [3] |
(1 mark) for any three
of: coercion, inclusion, overloading, parametric.
|
||
(b) | Explain the benefits of polymorphism in object-oriented programming. | [2] |
Adding a new
type does not require new code (1 mark). One name can be used to refer to one concept (1
mark). Award (1 mark) for any alternative benefit.
|
||
(c) | Consider the following declaration of a Stack in
C++: template <class T> public:
|
|
(i) The polymorphic function peek
takes a reference to a non-empty stack s and returns the top item of s without
discarding any items in s. Copy and complete the following definition of peek. template <class T>
|
[4] | |
template <class
T> T peek(Stack<T> & s) { T item; [1] item = s.pop(); [1] s.push(item); [1] return item; [1] }; For alternative solutions, the following scheme should be used: local variable declaration of type T (1 mark); assignment of top item to item (1 mark); pushing the top item back on the stack (1 mark); returning the item (1 mark).
|
|
|
(ii) The polymorphic function
reverse takes a reference to a stack s and changes it so that its items are in reverse
order. Copy and complete the following definition of reverse. template <class T>
|
[6] | |
template
<class T> void reverse(Stack<T> & s) { Stack<T> t; [1] while (!s.empty()) [2] t.push (!s.pop()); [2] s = t; [1] }; Local variable declaration of type Stack<T> (1 mark); use of loop (1 mark) with appropriate guard (1 mark); pop item from s (1 mark) and push it on t (1 mark); assign the local variable to s (1 mark).
|
||
(iii) The polymorphic function drop takes a
reference to a stack s and an integer n, and removes the first n items from s. If n is
greater than the number of items in s, then all items in s are removed. Copy and complete the following definition of drop. template <class T>
|
[5] | |
template <class T> void drop(Stack<T> & s, int n) { if (n>s.size()) [1] n = s.size(); [1] for (; n != 0; n--) [2] s.pop(); [1] }; Test the size of the stack (1 mark); limit n to size of stack (1 mark); each correct loop guard and decrement (1 mark); use of pop in loop (1 mark). |