Consider the following definition of a polymorphic Stack
template <class T>
class Stack {
private:
T* TopOfStack;
public:
Stack(); // Create a new stack.
void Push(T); // Push an item onto the stack.
T Pop(); // Remove the item from the top of the stack.
int Size(); // Return the number of items in the stack.
int IsEmpty(); // Return 1 if the stack is empty, 0
otherwise.
};
(a)One form of polymorphism in C++is overloading Explain,with reference
to an example,the term overloading [3marks ]
Overloading
is use of the same operator or function name;(1 mark)
For arguments of different types;(1 mark)
An appropriate example;(1 mark)
(b)Declare a pointer to the Stack class,called x instantiated with
an int type,and show how this could be allocated using the new operator.[2
marks ]
stack<int>* x = new Stack();
And the following marking scheme should be
used:
Correctly declaring the pointer with the int type;(1 mark)
Correctly allocating the object.(1 mark)
[2 marks ]
(c)Implement the template function Reverse the signature of which
is given below, such that it takes a reference to a stack of type
T and reverses the stack.You may use any of the member functions in
the class Stack necessary.
template<T>
void Reverse(Stack& T) [5 marks ]
A sample
definition of Reverse follows:
template<T>
void Reverse(Stack<T>& s) {
Stack<T> temp= new Stack();
while(!s.IsEmpty()) {
temp.Push(s.Pop());
}
s= temp;
}
And the following marking scheme should be used:
Declaring a local temporary copy of the stack;(1 mark)
Declaring a suitable iterative structure;(1 mark)
Bound by the empty stack condition;(1 mark)
Pushing the most recently popped item onto the new stack;(1
mark)
And returning the reference to the new stack.(1 mark)
[5 marks ]
(d)Implement the template function Search the signature of which
is given below,such that it takes a reference to a Stack s and an
object o and searches the stack for first occurrence of o If found,o
should be removed from the stack,leaving the rest of the stack unchanged,otherwise
the stack should remain unchanged.You may assume that suitable overloadings
of the == operator are available.[5 marks ]
A
sample definition of Search follows:
void Search(stack<T>& s, <T> o) {
<T>item;
Stack<T> TempStack= new Stack();
while(!s.IsEmpty() && (item= s.Pop())!= o) {
TempStack.Push(item);
}
while(!TempStack.IsEmpty()) {
s.Push(Tempstack.Pop());
}
}
And the following marking scheme should be used:
Iterating through the source stack s (1 mark)
Until a match is found,or no items remain to check;(1 mark)
And storing items on a temporary stack;(1 mark)
Iterating back through the temporary stack;(1 mark)
Replacing the non matching items back on the source stack.(1
mark)
[5 marks ]
|