Friend Function and Class
In some
cases you need to access the private data members of a class from non member
functions. In such situations you must declare the function as friend function
of the class. This friend function seems to violate the data hiding feature of
OOP concept. However, the function that accesses private data must be declared
as friend function within the class. With friend functions data integrity is
still maintained.
Sometimes
you may need to make, one or all the member functions of a class friend to
other class. For that we declare class or member function as the friend to the
other class so that one or all the member functions of the declared class will
be friend to the class within which it is declared.
Example:
class
breadth;
class length
{
private:
......
public:
......
friend int
add(length, breadth); //friend function declaration
};
class
breadth
{
private:
......
public:
......
friend int
add(length, breadth); //friend function declaration
};
int add(
length l, breadth b) { }
1. Write
a class for instantiating the objects that represent the two-dimensional
Cartesian coordinate system.
A. make a
particular member function of one class to friend function in another class for
addition
B. make
other three functions to work as a bridge between the classes for
multiplication, division and subtraction.
C. Also
write a small program to demonstrate that all the member functions of one class
are the friend functions of another class if the former class is made friend to
the latter.
Make least
possible classes to demonstrate all above in single program without conflict.
Write a
class to store x, y, and z coordinates of a point in three-dimensional space.
Using operator overloading, write friend functions to add, and subtract the
vectors.
No comments:
Post a Comment