December
1998 QUESTION 3 Total Marks: 20 Marks |
Click here to access other
questions
SUGGESTED SOLUTIONS
|
(a) | What is a friend function in C++? | [2] |
A friend function
permits a non-member function of a class (1 mark) to access the private data sections of
that class (1 mark).
|
||
(b) | Give one situation when a friend function might be used in C++. | [1] |
Either a
friend function is commonly used with operator overloading (1 mark) or when a function
requires access to data or methods in two separate classes (1 mark).
|
||
(c) | An airport has a number of stands where
an aeroplane may be parked. When a passenger is checked in for a flight on an
aeroplane, the weight of the passenger and his/her luggage is added to the weight of the
aeroplane. If the aeroplane is too heavy, it cannot take off. Consider the classes below. class Aeroplane { class Passenger { class Airport {
|
|
(i) Implement the constructor Passenger that takes two integers a and b and sets weight to a and luggage to b. Ensure that the
default value of weight is 75 and luggage is 25.
|
[3] | |
void Passenger::Passenger(int a=75, int b=25) { | [2] | |
weight = a; luggage = b; };
|
[1] | |
(ii) Give the definition of the Airport method check_in that takes a stand number (an integer index for an aeroplane) and a passenger, and performs the check-in procedure detailed above. | [3] | |
void check_in(int i, Passenger p) | [1] | |
Aeroplane *a = stand[i]; | [1] | |
a -> weight += p.weight + p.luggage; | [1] | |
}; (1 mark) for a correct signature; (1 mark) assigning local variable pointer the correct aeroplane; (1 mark) for accumulating the weight of the aeroplane
|
||
(iii) Give the dedinition of the Airport take_off that takes a stand number and an integer maximum take_off weight, and removes the aeroplane from the Airport (by replacing its entry with a NULL pointer) if it is not too heavy. If the aeroplane is too heavy, print error message. | [4] | |
void take_off(int i, int max) | [1] | |
if (stand[i] -> weight > max) | [1] | |
cout << "The place is too heavy" << endl; | [1] | |
else | ||
stand[i] = NULL; | [1] | |
}; (1 mark) for a correct signature; (1 mark) for correct if statement; (1 mark) for error message; (1 mark) for removing aeroplane.
|
||
(iv) Give the definition of the Airport method land that takes an aeroplane, and assigns it to
the first free stand in the airport and prints the number of the chosen land. You may assume that a spare stand exists. |
[7] | |
void land(Aeroplane a) | [1] | |
for (int i=0; i<30; i++) | [2] | |
if (stand[i] == NULL) { | [1] | |
cout << "Landing at " << i << endl; | [1] | |
stand[i] = &a; | [1] | |
return; | [1] | |
} | ||
}; (1 mark) for a correct signature; (1 mark) for using loop and (1 mark) for correct guard; (1 mark) for testing if the stand is free; (1 mark) for message; (1 mark) for assigning address of a; (1 mark) for leaving the loop (if not done, so by a loop test). |