Presentation is loading. Please wait.

Presentation is loading. Please wait.

Friend Functions 04/12/10. Today  Use reference parameters when passing an object.  Use friend functions with a class.

Similar presentations


Presentation on theme: "Friend Functions 04/12/10. Today  Use reference parameters when passing an object.  Use friend functions with a class."— Presentation transcript:

1 Friend Functions 04/12/10

2 Today  Use reference parameters when passing an object.  Use friend functions with a class.

3 Pass Objects By-reference  More efficient  Opens possibility of changing Object  const in front to protect  Sec6.4/point/point1.cpp Equal function compares two points Equal function compares two points

4 Friend Functions

5 Use of Accessors Awkward  An equal function is in the point program. sec6.4/point1.cpp sec6.4/point1.cpp  Used accessors, but awkward  Instead use friend functions. Sec6.4/point1a.cpp Sec6.4/point1a.cpp

6 Friend function  Allows access to private member variables  Doesn't have to use accessors  Placed in class definition  "friend" in front of definition  Is not a member function Definition does not need class name Definition does not need class name

7 When to Use friend Function  Function involving two objects  Objects equally important  Not appropriate to make it a member function of either object

8 Midpoint Example  Want to add a function to the point class that finds the midpoint of two points.  Why should it be a friend function.  Example of a function that returns an object.  point1b.cpp

9 Another example  Sec6.4/timer/TIMER Make a copy of timer.cpp to work on. Make a copy of timer.cpp to work on.

10 Overloaded Operators

11 Operator Overload  Would like to be able to use == to compare points.  Instead of a friend function  example sec6.4/point/point2.cpp

12 Overloaded Operators  Syntax returntype operator op (parameters);

13 Overloaded Operators //friend function friend bool equal(Point C, Point D); //operator overload friend bool operator==(Point C, Point D);

14 Overload of *  Multiplication of fractions  sec6.4/fracOps.cpp Finish the friend function Finish the friend function Change the friend function to operator overload Change the friend function to operator overload

15 On Your Own  Write an overload of == to compare the volume of two Cylinders like those on p. 227 #3

16 Inline Function  Can give the function definition within the class definition.  Point class on next slide has in-line functions. One of them is the default constructor.

17


Download ppt "Friend Functions 04/12/10. Today  Use reference parameters when passing an object.  Use friend functions with a class."

Similar presentations


Ads by Google