April
1999 QUESTION 5 Total Marks: 20 Marks |
Click here to access other
questions
GRADE A
|
(a) | Encapsulation is an important concept in object-oriented programming. Explain what is meant by encapsulation and give one advantage of it. | [3] |
Encapsulation is the
grouping of essential information together, so that is can be treated as a whole, one can
manipulate encapsulated object without regard of its operations or internal behaviour. Advantage: Provide data hiding and abstraction.
|
||
The following declaration of a class Stack in
C++ is one example of an encapsulated data type. template
<class T> public:
|
||
(b) | The Stack class implements the stack data type as an array of 100 items. State one advantage and one disadvantage of implementing a stack in this way. | [2] |
Advantage: Array is
easy to manipulate and access. Disadvantage: Array size is fixed, hence it cannot shrink or expand as wished. Using array also results in wasting of space for unused location.
|
||
(c) | Give an implementation of the method size. | [1] |
int get_size() { return size;}
|
||
(d) | Give an implementation of the method push that prints an appropriate error message if the stack is full. | [3] |
template <class
T> void push(T in) { if (size > 100) cout << "Stack is full!" << endl; else { stack[size-1] = in; size++; } };
|
||
(e) | Give an implementation of the method pop that prints an appropriate error message if the stack is empty. | [3] |
template <class
T> T pop() { if (size <= 0) cout << "Stack is empty!" << endl; else { T item = stack[size-1]; size--; } return item; };
|
||
(f) | Implement a function filter that takes a stack s and an item c of type T, and returns
a new stack that contains only the elements of s that are less than c. You may assume the operator < is defined for all types. |
[6] |
Stack<T>
filter(Stack<T> & s, T c){ T item; Stack<T> temp; while (s.get_size() != 0){ item = s.pop(); size--; if (item < c) temp.push(item); } s = temp; return s; }; |
||
(g) | State an alternative way to implement the stack encapsulated data type and explain how it improves upon an array implementation. | [2] |
Linked list. In linked
list, the stack makes use of pointer. One can add and allocate the space for push anytime
he/she wants without having to limit the size allocated earlier. It is more dynamic, and
if the memory space is large, one can even disregard the full stack situation.
|