898F3 Programming in C++: The Money Class
1. Question 1 (25 pts) Write and then test a Money class, which represents amounts of UK currency. The value is implemented as a single integer value that represents the amount of money as if it were converted to all pennies. For example, £ 9.95 would be stored as the value 995. This integer for the amount of money is stored in a member variable called allPence: what ‘type’ would you be using for this variable? Discuss the reason why you chose that ‘type’.
Make sure that you code is written in such a way to check for possible errors on the values that are used as ‘input’ to build the class, and that your program terminates in a ‘controlled way’ in case of wrong format of the input variables.
The class Money has three constructors:
- one to initialise the object so that its value represents an amount with the ‘pounds’ and ‘pence’ given by the arguments (‘£ pounds.pence’). If the amount is negative, then both ‘pounds’ and ‘pence’ should be negative;
- one to initialise the object so its value represents ‘£ pounds.00’;
- one default constructor to initialise the object so its value represents ‘£ 00.00’;
The class Money has two ‘friend’ functions: add and equal. The function add returns a Money object whose value is the sum of the values of its two arguments; a function equal returns true if the two objects that are compared have values that represent equal amounts of money. In these functions the input parameters could be called either ‘by value’ or ‘by reference’. What would be the di erence in these two cases? Which one is a more e cient implementation? In the call ‘by reference’ how would you indicate to the compiler that the input parameters of your functions do not change the value of the parameters? Implement and test the functions (in separate files) using the call-by-value and call-by-reference methods and show that you get the same result.
The class Money has two functions, input and output to input the amount of money to compare and output the result of the comparison. Test your class with a test function that asks for an amount of money (twice), prints it and then compares the two amounts printing which one is the highest. Then add the two amounts and print out the total.
2. Question 2 (25 pts) Now overload the binary operators ‘+’, ‘-’ and ‘==’ so that they will accept arguments of the class type Money. Overload also the unary operator ‘-’ when it is used to mean negation (e.g., when it is used to set the value of a variable x equal to the negative of the value of the variable y, x = -y). Test the new class built overloading these operators and, in the case of ‘+’ and ‘==’, check that you obtain the same results you had when using the functions add and equal.
Finally, overload the operators ‘<<’ and ‘>>’ so that you can input/output the values from/to a file in the correct format.