April
1999 QUESTION 3 Total Marks: 20 Marks |
Click here to access other
questions
GRADE A
|
(a) | One form of Polymorphism in C++ is operator overloading. | |
(i) Explain, using an appropriate example, the term operator overloading. | [3] | |
(ii) Consider the polymorphic expression 5 == 5.0 in C++. What form of polymorphism is this an example of? Explain your answer. | [2] | |
(i) Overloading allows
same function name or operator to be used on different argument type. The function is
called based on its signature. The number and type of argument in the parameter list. (ii) Coercion. The two argument are of different types.
|
||
Consider the declaration of the class String below. You are to write overloaded
operator functions for strings. class String
{
|
||
(b) | Give an implementation of the overloaded operator < that takes two strings by reference and returns 1 if the first is less than the second, or 0 otherwise. | [2] |
int operator <
(String &f, String&s) { int j = f.length(); int k = s.length(); int i = -1; Do { i++; if (f.char_at(i) < s.char_at(i)) return 1; } while (i < j && i < k); return 0; };
|
||
(c) | Give the implementation of the overloaded operator == that takes two strings by reference and returns 1 if they are equal, or 0 otherwise. | [6] |
int operator ==
(String &f, String&s) { int j = f.length(); int k = s.length(); if (j != k) return 0; int i = -1; Do { i++; if (f.char_at(i) != s.char_at(i)) return 0; } while (i < j); return 1; };
|
||
(d) | Give an implementation of the function cmp that takes two strings by reference and returns -1 if the first is less than the second, 0 if they are equal, or 1 is the first is greater than the second. | [4] |
int String cmp
(String &f, String&s) { if (f < s) return -1; else if (f == s) return 0; else return 1; }; |