Recitation - Jan 31, 2011
- Friends and Members
- friend allows function to access private data without being a member function.
- Example from fraction class
//--------------- FRAC.H ---------------
// declaring a function as a friend
class Fraction
{
friend bool Equals(Fraction x, Fraction y);
public:
...
private:
...
};
//--------------- FRAC.CPP ---------------
// friend function definition
bool Equals(Fraction x, Fraction y)
{
return (x.numerator * y.denominator == y.numerator * x.denominator);
}
operator overloading
- b = a; // Same as b.operator=(a);
-
f3 = f1 + f2;
As a friend function:
friend Fraction operator+(const Fraction& f1, const Fraction& f2);
Or as a member function:
Fraction Fraction::operator+(const Fraction& f);
Another example:
n3 = n1 + n2; // n1 is the calling object, n2 is the argument
n3 = n1.operator+(n2);
What about the '<<' operator?
cout << a;
- Add multiplication functionality to fraction class
HW2 discussion
- Input format
- Increment function
- Code simplification (e.g. preventing code duplication)
"How and where do I need to check to see whether a given date is actually valid?"
- Compare function is formed in a similar way as f1.Add(f2)
- TESTING - sample.cpp driver program. Make sure your code performs as detailed in the specifications.
Suggestions from HW1
- Do NOT include main() in .cpp or .h class files. Will cause redefinition compile error for driver.cpp program.
- Make sure your program compiles.
- Make sure to document code where appropriate.
- Try to avoid code duplication.
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;
}
Followups
- How can constant data members be initialized?
- Initialize in the member initializer list.
- IMPORTANT: constructors for objects in the initializer
list are called in the order seen in the member declaration, NOT the
order coded in the member initializer list. Therefore, to avoid confusion, it
is best to ensure the orders are equivalent.