INSTRUCTOR
HUMA RASHID
INSTRUCTOR
HUMA RASHID
FRIEND FUNCTIONS
Friend functions of an object can "see" inside the
object and access private member functions and
data.
To declare a function as a friend of a class,
precede the function prototype in the
class definition with the keyword friend.
WHEN
NEEDED?
class rectangle {
friend void set_value(rectangle&, float); // friend declaration
private:
float height;
float width;
int xpos;
int ypos;
public:
rectangle(float, float); // constructor
void draw(); // draw member function
void posn(int, int); // position member function
void move(int, int); // move member function
float get_height(); // access function
void set_height(float); // access function
};
void set_value(rectangle &rc, float h)
{
rc.height = h;
}
void main()
{
rectangle rc(1.0, 3.0);
set_value(rc, 10.0);
}
FRIEND FUNCTION PROGRAM EXERCISE
 Write a class complex that has two private attributes one for storing real part and
other for imaginary part. SetNumber function to set the real part and imaginary part.
PrintNumber function to display them on screen.
 Write a function to calculate Sum of two complex numbers(Hint: use friend function
)
2 + 3i
3 + 7i
--------------
5 + 10i
FRIEND CLASS PROGRAM EXERCISE
 Modify the program you have written for last exercise. Introduce a class
calculator that adds real part of complex number in a function and
return int. Similar function for sum of imaginary part. Make the class
friend of class complex.

Friend Function Computer Programming.pdf

  • 1.
  • 2.
    FRIEND FUNCTIONS Friend functionsof an object can "see" inside the object and access private member functions and data. To declare a function as a friend of a class, precede the function prototype in the class definition with the keyword friend.
  • 3.
  • 5.
    class rectangle { friendvoid set_value(rectangle&, float); // friend declaration private: float height; float width; int xpos; int ypos; public: rectangle(float, float); // constructor void draw(); // draw member function void posn(int, int); // position member function void move(int, int); // move member function float get_height(); // access function void set_height(float); // access function };
  • 6.
    void set_value(rectangle &rc,float h) { rc.height = h; } void main() { rectangle rc(1.0, 3.0); set_value(rc, 10.0); }
  • 11.
    FRIEND FUNCTION PROGRAMEXERCISE  Write a class complex that has two private attributes one for storing real part and other for imaginary part. SetNumber function to set the real part and imaginary part. PrintNumber function to display them on screen.  Write a function to calculate Sum of two complex numbers(Hint: use friend function ) 2 + 3i 3 + 7i -------------- 5 + 10i
  • 12.
    FRIEND CLASS PROGRAMEXERCISE  Modify the program you have written for last exercise. Introduce a class calculator that adds real part of complex number in a function and return int. Similar function for sum of imaginary part. Make the class friend of class complex.