April 1999
OP216: OBJECT-ORIENTED PROGRAMMING

QUESTION 5

Total Marks: 20 Marks

Click here to access other questions

Click to access
SAMPLE STUDENT'S SOLUTIONS
for Question 5

 

(a) Encapsulation is an important concept in object-oriented programming. Explain what is meant by encapsulation and give one advantage of it.

 

[3]
The following declaration of a class Stack in C++ is one example of an encapsulated data type.

template <class T>
class Stack {
private:
   T stack[1000];  // A stack is an array of 100
                   //items
   int size;    // The number of items in the stack

public:
   Stack();   // Constructor that initialises the
              // stack
   int get_size();  // Return the number of items
                    // in the stack
   void push(T);    // Place an item at the top
                    // of the stack
   T pop();         // Remove an return the top
                    // item on the stack
}

 

(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]
(c) Give an implementation of the method size.

 

[1]
(d) Give an implementation of the method push that prints an appropriate error message if the stack is full.

 

[3]
(e) Give an implementation of the method pop that prints an appropriate error message if the stack is empty.

.

[3]
(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]
(g) State an alternative way to implement the stack encapsulated data type and explain how it improves upon an array implementation. [2]