Download presentation
Presentation is loading. Please wait.
Published byStephanie Wood Modified over 9 years ago
2
Session Objectives Define Static data member Static member functions in a class Object as Function Argument Friend Function Friend Class
3
FRIEND FUNCTIONS Why it is used? - The concept behind the encapsulation and data hiding restrict the non-member function from accessing the private members of the class. The best way to access a private data member by a non- member function is to change a private data member to a public. but it violates the whole concept of data hiding and encapsulation. To solve this problem friend functions are used when we can access the private or protected members.
4
Friend informs the compiler that the function is not a member func.Of the class. Syntax : friend func_name(arguments); Member FunctionFriend Function It is a part of class definition and is invoked by a particular object It is no a part of a class It can access the data depending upon whether the function is private or protected It can access any data irrespective of the private or public or protected access
5
#include class book { private : int bno; char bname[20]; public: void getdata(); friend void show(book); }; void book::getdata() { cin>>bno>>bname; } void show(book bk) { cout<<bk.bno<<bk.bname; } void main() { book b; clrscr(); b.getdata(); show(b); getch(); }
6
FRIEND FUNCTIONS To access the private member of the class inside the friend function the object of the class should be passed as an argument to the function #include class second; class first { private : int no; public: first(int n); friend int add(first,second); }; class second {
7
private : int n1; public: second(int); friend int add(first,second); }; first ::first(int n) { no=n; } second ::second(int n) { n1=n; } int add(first f,second s) { cout<<"First class="<<f.no<<endl; cout<<"Second class=“ <<s.n1; return f.no+s.n1; } void main() { first f(10); second s(20); clrscr(); cout<<"\n The Result is "<<add(f,s); }
8
FRIEND CLASS The private members of one class can be accessed from the member functions Of another class by making them as friends #include class second; class first { private : int no; public: friend class second; first(int n) {
9
no=n; }}; class second { public: void show(first f) { cout<<f.no; } }; void main() { first f(10); second s; s.show(f); getch(); }
10
The friend function acts as a bridge between two objects of different classes which can access even the private members of the class A friend class is a class whose members functions are all friend functions of another class
11
EXERCISES Define “friend “ keyword & its use? Difference between friend function and member functions? Explain the use of friend function? Discuss about friend class?
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.