Page 107 - DCAP404 _Object Oriented Programming
P. 107
Object-oriented Programming
Notes Since private data members are available only to the particular class and not to any other part of
the program, a non-member function cannot access these private data. Therefore, the friend
function is a special type of function which is used to access the private data of any class. In other
words, they are defined as non-member functions with the ability to modify data directly or to
call function members that are not part of the public interface. The friend class has the right to
access as many members of its class. As a result the level of privacy of the data encapsulation gets
reduced. Only if it is necessary to access the private data by non-member functions, then a class
may have a friend function, otherwise it is not necessary.
Did u know? Is friend function a member of a class?
A friend function is a function that is not a member of a class but has access to the class’s
private and protected members.
Let us look at a sample program given below to access the private data of a class by non-member
functions through friend function. The program declares a private class example representing
variable x and function to input the value for the same. The friend function to display the value
of x takes an object as argument with the help of which private variable x can be accessed.
#include <iostream.h>
#include <conio.h>
class example
{
private:
int x; .
public:
void getdata()
{
cout << “Enter the value ofx”<< “\n”;
cin >> x;
}
friend void disp(example);
};
void disp(example eg)
{
cout << “Display the entered number”<< eg.x<< “\n”;
}
main()
{
example egl;
eg1.getdata();
disp(eg1);
getche();
}
100 LOVELY PROFESSIONAL UNIVERSITY