August 1999
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) Explain, using an appropriate example, the term coercion.

 

[3]
(b) Consider the following declaration of a Stack in C++:

template <class T>
class Stack {
private:
     //  Some private 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 on the stack
     int empty(); // Return 1 if the stack is empty, otherwise return 0

}

(i) 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) {
  // Function definition
} ;

(ii) The polymorphic function Split takes a reference to a stack s and splits s up into two stacks. The function returns a stack which consists of the first n items of s, and also removes the first n items from s. It there are less than n items in s, then the function returns a copy of s, and s has all its items removed.

For example, if the integer stack s = (8,7,6,5,4,3,2,1) were passed to
x = Spilt(s,3),
then the function would return the stack
x= (8,7,6), and s = (5,4,3,2,1).
Copy, and complete the following definition of Spilt :

template <class T>
Stack<T> Stack ::Spilt(Stack<t>& s, n) {
    //Function definition
};

(iii) The polymorphic function Slice takes a reference to a stack s, and two integer parameters x and y. The function removes the xth to the yth items from s, inclusive. If there are less than x items, then s remains unchanged; if there are less than y items, then all items from x to the bottom of the stack are removed. Copy and complete, the following definition of Slice :

template <class T>
void Stack :: Slice(Stack<T>& s, x, y) {
    //Function definition
}

 

 

 

 

 

 

 

 

[5]

 

 

 

[6]