Revision of Overloading and Assert in Preparation For Assignment Two
Revision of Overloading and Assert in Preparation For Assignment Two
• Overloading a function: more than one function in the same class having the same
name but differing either in the number of parameters or the types of their
parameters.
• The easiest way to remember this: the functions’ parameters should qualify any one
or more than one of the following conditions:
N.B. You should not use the same function name for two
unrelated functions.
Assignment Two 2022: Question One
In this question, students were required to write a C++ program that includes a function
to calculate the discount applicable on the price of an item. The function should have
three arguments: the price as a reference parameter to a double, the discount as a
double value, and a bool to indicate if the discount is calculated as a percentage or a
fixed amount. The parameter to indicate whether the discount is a fixed amount, or a
percentage, should be called fixed. When fixed is true, it will indicate that the discount
is a fixed amount and when it is false, the discount is a percentage. The function
should calculate the discount and modify the price of the item accordingly.
The function should check that the discount is not negative and that the price does not
drop to zero or below zero after applying the discount. The following solution uses the
assert() function to ensure that the discount is not negative and that the price does not
drop to zero or below zero once the discount is applied.
Solution using Assert
1. //This program demonstrates using the assert statement to ensure
the input
2. //and discount calculation meet certain criteria.
3. //The discount value may not be negative and the price resulting
from the
4. //discount may not be 0 or below 0.
5.
6. #include <iostream>
7. #include <cassert>
cout << endl << "Please enter the price and discount separated by spaces
" << endl;
cin >> itemPrice >> itemDiscount;
cout << "Is the discount a fixed amount or a percentage? Type F for a
fixed amount, P for a percentage:";
cout.precision(2);
cout << "The discounted price for R" << itemPrice << " is R " <<
discountPrice << endl;
return 0;}
Removing Assertions
• To remove assert statements
No need to delete them manually
Include:
#define NDEBUG
14