A function without the typical scope resolution operator can be made a "friend" of a class
- Friends can access private data members
- The usual 146-style function declaration is used.
ret_type fn_name (var_list)
Where var_list must likely includes a reference parameter of the class
- In the class definition prior to public or private the statement is labeled as friend
- Regardless of where you place it, the friend function is public
- One CLASS can be a friend of another class
Requires a forward declaration in the class defined second
- It's best not to have many friends :)
References and Overloaded Operators
- A reference is the name of a storage location
int somnum = 9;
int &othernum = somenum;
//both somnum and othernum refer to the
same storage location in RAM that contains a 9
- Can return a reference to some member variables
- Can return a reference to a class
- Return type includes & after the type
- Not a good idea in general
- Returns an alias to the variable
- Useful for some overloading of operators
- Permits the use of the class as an l-value
class abc {
public:
int & f(); // used for any l-value invocation
const int& f() const; // used for any r-value invocation
...
};
Overload input and output operators
- Need to be friends
- Operators are members of other classes
- Requires istream or ostream as a parameter
- For example:
void operator<< (ostream & sout, const Rational & x)
{
cout << x.NumeratorValue << "/" << x.DenominatorValue;
}
Assignment, increment and Decrement
- You must overload the assignment operator (=) as a member function
- If you do not overload the assignment operator, C++ creates one for
you that copies the member variables.
If pointers are in the class then
this is probably NOT what we want to happen.
- Increment and decrement have two versions - prefix and postifix
Rational operator++(); //prefix version
Rational operator++(int); //postfix version