December 1998
OP216: OBJECT ORIENTED PROGRAMMING

QUESTION 2

Total Marks: 20 Marks

Click here to access other questions

Click to access
SUGGESTED SOLUTIONS
for Question 2

 

(a) List three types of polymorphism found in C++.

 

[3]
(b) Explain the benefits of polymorphism in object-oriented programming.

 

[2]
(c) Consider the following declaration of a Stack in C++:

template <class T>
class Stack {
private:
  ...         \\ Some declarations

public:
  Stack();     \\ Constructor that initialises
                    the stack
  void push(T)  \\ place an item at the top of the
                    stack
  T pop();      \\ remove and return the top
                    item on the stack
  int size();   \\ return the number of items
                    in the stack
  int empty();  \\ return 1 if the stack is empty,
                  otherwise return 0
}

 

(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>
T peek(Stack<T> & s) {

};

 

[4]
(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>
void reverse(Stack<T> & s) {

};

 

[6]
(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>
void drop(Stack<T> & s, int n) {

};

[5]