April 1999
OP216: OBJECT-ORIENTED PROGRAMMING

QUESTION 2

Total Marks: 20 Marks

Click here to access other questions

GRADE A
Student's solutions are indicated in green.
Return to Question 2

 

Singapore Zoo requires a program to record information about its animals. You are to write such a program.

 

(a) Each animal in the zoo has a name (a character string) and a feeding time (an integer). Give an implementation of a class Animal that contains: (1) these private data items; (2) a constructor that takes a name, and sets the animal's name to it and its feeding time to 1200; (3) a method display that prints the name of the animal; and (4) an assessor method for the feeding time of the animal. [7]
class Animal
{   private :
         char *name;
         int feeding_time;
    public:
         Animal (char *nam)
         {   name = nam;
             feeding_time = 1200;
         }
         void Display (void)
         {   cout << name;
         }
         int access_f_time (void)
         {   return feeding_time;
         }
};

 

(b) The zoo itself is an array of 500 animals in addition to an integer that records the number of animals in the zoo.
(i) Give the definition of a class Zoo that contains: (1) these private data items; and (2) a default constructor that initialises the number of animals to 0. [4]
(ii) Give the implementation of a method display that displays the name of every animal in the zoo. [2]
(iii) Give the implementation of a method next_feeding_time that takes a time (an integer) and returns the next feeding time of an animal in the zoo after the given time.
State any assumptions you make.
[7]
(i)
class zoo
{   private:
         Animal array[500];
         int num;
    public:
         zoo() {num = 0;}
};

(ii)
void zoo::display(void)
{  int i;
   for (i=0;i<500;i++)
      cout << "The name of animal number " << 
      i+1 << "is " << array[i].name << endl;
}

(iii) Assumption: Feeding time that is right after the taken time will be displayed.

int zoo::next_feeding_time(int a)
{  int i;
   int x;
   x = 2400;
   for (i=0;i<500;i++)
      if ((array[i].feeding_time > a) &&  
      (array[i].feeding_time < x)
          x = array[i].feeding_time;
          return x;
}