Recitation - Feb 7, 2011
Operator Overloading
- Increment (i.e. ++) and Decrement (i.e. --) operators
- Each have two versions prefix and suffix (postfix).
- Prefix
- In C, if x is an int, ++x is the same as x += 1 which is the same as x = x+1.
- The value of x returned is the new value of x.
- Postfix
- x--
- The value of x returned is the old value of x.
- Allows one to first use the value and then increment it.
- Example:
int a, b=0, tmp;
// The below two statements are equivalent.
//a=b++;
a=(tmp=b, b=b+1, tmp);
cout << "a: " << a << endl;
cout << "b: " << b << endl;
Commonly used in loops.
Overloading the increment (++) operator
- Prefix (increment and return)
- ++A and A++ how can the overloaded function tell the difference
- A.operator++()
- Postfix (return and increment)
- Note: prefix version returns a reference, postfix does not.
- Example - IntPair Class
Overloading the addition assignment (+=) operator
To be completed in class.
Complete assignment and demonstrate to the TA your code works. Then email completed exercise (main.cpp, frac.h, frac.cpp, makefile) to TA.
Total of 3 points and 1 bonus point.
Points breakdown:
- 1.5 points for increment (postfix and prefix versions)
- 1.5 points for decrement (postfix and prefix versions)
- (Bonus) 1 point for addition assignment (+=) operator (not required)
Hint: make use of code already provided in the class.
Thought Exercise
Without the break, will the while loop ever terminate?
#include
using namespace std;
int main()
{
float f = 0;
float prev_f = f;
cout << "FLT_MAX: " << FLT_MAX << endl;
while (f != FLT_MAX) {
prev_f = f;
f++;
if (prev_f == f) {
cout << "prev_f and f both equal: " << prev_f << endl;
break;
}
}
return 0;
}
Explanation
- Floating points allow for a wider range of values for an equivalently sized int.
- However, with the increase in range of values represented, comes a lack of precision for some values.
- Typical, floating point representation in a computer.
- sign bit, exponent, and significand (mantissa)
- 1 bit, 8 bit, and 23 bit (not guaranteed but common for float)
- formula to extract number (IEEE 754 single precision binary floating-point format: binary32):
-1^(sign-bit) (1 + sum over i from i equals 1 to 23 b_i 2^(-i)) * 2^(exp-127)
16777216 = 1.00000000000000000000000 * 2^24
1 = 1.00000000000000000000000 * 2^0
16777216 = 1.00000000000000000000000|0 * 2^24
1 = 0.00000000000000000000000|1 * 2^24
16777217 = 1.00000000000000000000000|1 * 2^24
Round (to zero, nearest even, infinity)
1.00000000000000000000000 * 2^24
which finally equals 16777216 in decimal
Followups
- How can constant (per-object) data members be initialized?
Additional Notes