SlideShare a Scribd company logo
1 of 12
Friend Function
C++ Friend function
If a function is defined as a friend function in C++, then the
protected and private data of a class can be accessed using the
function.
By using the keyword friend compiler knows the given function is a
friend function.
For accessing the data, the declaration of a friend function should
be done inside the body of a class starting with the keyword friend.
Declaration of friend function in C++
1. class class_name
2. {
3. friend data_type function_name(argument/s); // syntax of friend
function.
4. };
In the above declaration, the friend function is preceded by the keyword friend.
The function can be defined anywhere in the program like a normal C++
function. The function definition does not use either the keyword friend or
scope resolution operator.
Characteristics of a Friend function:
 The function is not in the scope of the class to which it has been
declared as a friend.
 It cannot be called using the object as it is not in the scope of that
class.
 It can be invoked like a normal function without using the object.
It cannot access the member names directly and has to use an
object name and dot membership operator with the member name.
It can be declared either in the private or the public part.
C++ friend function Example
#include <iostream>
2. using namespace std;
3. class Box
4. {
5. private:
6. int length;
7. public:
8. Box(): length(0) { }
9. friend int printLength(Box); //friend function
10. };
C++ friend function Example
int printLength(Box b)
12. {
13. b.length += 10;
14. return b.length;
15. }
16. int main()
17. {
18. Box b;
19. cout<<"Length of box: "<<
printLength(b)<<endl;
20. return 0;
21. }
Output:
Length of box: 10
C++ friend function Example 2
1. #include <iostream>
2. using namespace std;
3. class B; // forward
declarartion.
4. class A
5. {
6. int x;
7. public:
8. void setdata(int i) {
10. x=i;
11. }
{
10. x=i;
11. }
C++ friend function Example 2
12. friend void min(A,B); // friend function.
13. };
14. class B
15. {
16. int y;
17. public:
18. void setdata(int i)
19. {
20. y=i;
21. }
22. friend void min(A,B); // friend function
23. };
24. void min(A a,B b)
25. {
26. if(a.x<=b.y)
27. std::cout << a.x << std::endl;
28. else
29. std::cout << b.y << std::endl;
30. }
C++ friend function Example 2
31. int main()
32. {
33. A a;
34. B b;
35. a.setdata(10);
36. b.setdata(20);
37. min(a,b);
38. return 0;
39. }
Output:
10
C++ Friend class
A friend class can access both private and protected members of the
class in which it has been declared as friend.
Example of a friend class.
1. #include <iostream>
2.
3. using namespace std;
4.
5. class A
6. {
7. int x =5;
8. friend class B; // friend class.
9. };
10. class B
11. {
12. public:
13. void display(A &a)
14. {
15. cout<<"value of x is : "<<a.x;
16. }
17. };
Example of a friend class.
18. int main()
19. {
20. A a;
21. B b;
22. b.display(a);
23. return 0;
24. }
Output:
value of x is : 5

More Related Content

What's hot

Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)Ritika Sharma
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++Paumil Patel
 
Classes and objects
Classes and objectsClasses and objects
Classes and objectsNilesh Dalvi
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator OverloadingNilesh Dalvi
 
Polymorphism In c++
Polymorphism In c++Polymorphism In c++
Polymorphism In c++Vishesh Jha
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member FunctionsMOHIT AGARWAL
 
Inline function
Inline functionInline function
Inline functionTech_MX
 
Constructor and Types of Constructors
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of ConstructorsDhrumil Panchal
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++Muhammad Waqas
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methodsShubham Dwivedi
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++Rabin BK
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams Ahmed Farag
 
Friend functions
Friend functions Friend functions
Friend functions Megha Singh
 

What's hot (20)

Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
 
Friend function in c++
Friend function in c++ Friend function in c++
Friend function in c++
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Polymorphism In c++
Polymorphism In c++Polymorphism In c++
Polymorphism In c++
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
Inline function
Inline functionInline function
Inline function
 
Constructor and Types of Constructors
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of Constructors
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++
 
This pointer
This pointerThis pointer
This pointer
 
Functions in C
Functions in CFunctions in C
Functions in C
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Friend functions
Friend functions Friend functions
Friend functions
 
Classes and objects in c++
Classes and objects in c++Classes and objects in c++
Classes and objects in c++
 

Similar to Friend function

Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)Asfand Hassan
 
Chapter23 friend-function-friend-class
Chapter23 friend-function-friend-classChapter23 friend-function-friend-class
Chapter23 friend-function-friend-classDeepak Singh
 
Chapter22 static-class-member-example
Chapter22 static-class-member-exampleChapter22 static-class-member-example
Chapter22 static-class-member-exampleDeepak Singh
 
Example for Abstract Class and Interface.pdf
Example for Abstract Class and Interface.pdfExample for Abstract Class and Interface.pdf
Example for Abstract Class and Interface.pdfrajaratna4
 
Object and class presentation
Object and class presentationObject and class presentation
Object and class presentationnafisa rahman
 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsRai University
 
Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objectsRai University
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsMayank Jain
 
Chapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classChapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classDeepak Singh
 
Lec_15_OOP_ObjectsAsParametersFriendClasses.pdf
Lec_15_OOP_ObjectsAsParametersFriendClasses.pdfLec_15_OOP_ObjectsAsParametersFriendClasses.pdf
Lec_15_OOP_ObjectsAsParametersFriendClasses.pdfAneesAbbasi14
 
OOP Week 3 Lecture 2.pptx
OOP Week 3 Lecture 2.pptxOOP Week 3 Lecture 2.pptx
OOP Week 3 Lecture 2.pptxwhoiam36
 
Chapter 7 C++ As OOP
Chapter 7 C++ As OOPChapter 7 C++ As OOP
Chapter 7 C++ As OOPAmrit Kaur
 

Similar to Friend function (20)

Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)
 
Chapter23 friend-function-friend-class
Chapter23 friend-function-friend-classChapter23 friend-function-friend-class
Chapter23 friend-function-friend-class
 
OOPs & C++ UNIT 3
OOPs & C++ UNIT 3OOPs & C++ UNIT 3
OOPs & C++ UNIT 3
 
Chapter22 static-class-member-example
Chapter22 static-class-member-exampleChapter22 static-class-member-example
Chapter22 static-class-member-example
 
Example for Abstract Class and Interface.pdf
Example for Abstract Class and Interface.pdfExample for Abstract Class and Interface.pdf
Example for Abstract Class and Interface.pdf
 
Object and class presentation
Object and class presentationObject and class presentation
Object and class presentation
 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objects
 
Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objects
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
C++ classes
C++ classesC++ classes
C++ classes
 
ccc
cccccc
ccc
 
cse l 5.pptx
cse l 5.pptxcse l 5.pptx
cse l 5.pptx
 
Chapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classChapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-class
 
Oop objects_classes
Oop objects_classesOop objects_classes
Oop objects_classes
 
Object Oriented Programming using C++ - Part 2
Object Oriented Programming using C++ - Part 2Object Oriented Programming using C++ - Part 2
Object Oriented Programming using C++ - Part 2
 
Lec_15_OOP_ObjectsAsParametersFriendClasses.pdf
Lec_15_OOP_ObjectsAsParametersFriendClasses.pdfLec_15_OOP_ObjectsAsParametersFriendClasses.pdf
Lec_15_OOP_ObjectsAsParametersFriendClasses.pdf
 
OOP Week 3 Lecture 2.pptx
OOP Week 3 Lecture 2.pptxOOP Week 3 Lecture 2.pptx
OOP Week 3 Lecture 2.pptx
 
Class and object
Class and objectClass and object
Class and object
 
Chapter 7 C++ As OOP
Chapter 7 C++ As OOPChapter 7 C++ As OOP
Chapter 7 C++ As OOP
 
Function overloading
Function overloadingFunction overloading
Function overloading
 

More from zindadili

Exception handling
Exception handlingException handling
Exception handlingzindadili
 
Exception handling
Exception handlingException handling
Exception handlingzindadili
 
Virtual function
Virtual functionVirtual function
Virtual functionzindadili
 
Operator overloaing
Operator overloaingOperator overloaing
Operator overloaingzindadili
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2zindadili
 
Polymorphism
PolymorphismPolymorphism
Polymorphismzindadili
 
Function overloading
Function overloadingFunction overloading
Function overloadingzindadili
 
Hierarchical inheritance
Hierarchical inheritanceHierarchical inheritance
Hierarchical inheritancezindadili
 
Hybrid inheritance
Hybrid inheritanceHybrid inheritance
Hybrid inheritancezindadili
 
Multiple inheritance
Multiple inheritanceMultiple inheritance
Multiple inheritancezindadili
 
Abstraction1
Abstraction1Abstraction1
Abstraction1zindadili
 
Access specifier
Access specifierAccess specifier
Access specifierzindadili
 

More from zindadili (20)

Namespaces
NamespacesNamespaces
Namespaces
 
Namespace1
Namespace1Namespace1
Namespace1
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Templates2
Templates2Templates2
Templates2
 
Templates1
Templates1Templates1
Templates1
 
Virtual function
Virtual functionVirtual function
Virtual function
 
Operator overloaing
Operator overloaingOperator overloaing
Operator overloaing
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Aggregation
AggregationAggregation
Aggregation
 
Hierarchical inheritance
Hierarchical inheritanceHierarchical inheritance
Hierarchical inheritance
 
Hybrid inheritance
Hybrid inheritanceHybrid inheritance
Hybrid inheritance
 
Multiple inheritance
Multiple inheritanceMultiple inheritance
Multiple inheritance
 
Abstraction1
Abstraction1Abstraction1
Abstraction1
 
Abstraction
AbstractionAbstraction
Abstraction
 
Access specifier
Access specifierAccess specifier
Access specifier
 
Inheritance
InheritanceInheritance
Inheritance
 
Enum
EnumEnum
Enum
 

Recently uploaded

Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........LeaCamillePacle
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 

Recently uploaded (20)

Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"
 

Friend function

  • 2. C++ Friend function If a function is defined as a friend function in C++, then the protected and private data of a class can be accessed using the function. By using the keyword friend compiler knows the given function is a friend function. For accessing the data, the declaration of a friend function should be done inside the body of a class starting with the keyword friend.
  • 3. Declaration of friend function in C++ 1. class class_name 2. { 3. friend data_type function_name(argument/s); // syntax of friend function. 4. }; In the above declaration, the friend function is preceded by the keyword friend. The function can be defined anywhere in the program like a normal C++ function. The function definition does not use either the keyword friend or scope resolution operator.
  • 4. Characteristics of a Friend function:  The function is not in the scope of the class to which it has been declared as a friend.  It cannot be called using the object as it is not in the scope of that class.  It can be invoked like a normal function without using the object. It cannot access the member names directly and has to use an object name and dot membership operator with the member name. It can be declared either in the private or the public part.
  • 5. C++ friend function Example #include <iostream> 2. using namespace std; 3. class Box 4. { 5. private: 6. int length; 7. public: 8. Box(): length(0) { } 9. friend int printLength(Box); //friend function 10. };
  • 6. C++ friend function Example int printLength(Box b) 12. { 13. b.length += 10; 14. return b.length; 15. } 16. int main() 17. { 18. Box b; 19. cout<<"Length of box: "<< printLength(b)<<endl; 20. return 0; 21. } Output: Length of box: 10
  • 7. C++ friend function Example 2 1. #include <iostream> 2. using namespace std; 3. class B; // forward declarartion. 4. class A 5. { 6. int x; 7. public: 8. void setdata(int i) { 10. x=i; 11. } { 10. x=i; 11. }
  • 8. C++ friend function Example 2 12. friend void min(A,B); // friend function. 13. }; 14. class B 15. { 16. int y; 17. public: 18. void setdata(int i) 19. { 20. y=i; 21. } 22. friend void min(A,B); // friend function 23. }; 24. void min(A a,B b) 25. { 26. if(a.x<=b.y) 27. std::cout << a.x << std::endl; 28. else 29. std::cout << b.y << std::endl; 30. }
  • 9. C++ friend function Example 2 31. int main() 32. { 33. A a; 34. B b; 35. a.setdata(10); 36. b.setdata(20); 37. min(a,b); 38. return 0; 39. } Output: 10
  • 10. C++ Friend class A friend class can access both private and protected members of the class in which it has been declared as friend.
  • 11. Example of a friend class. 1. #include <iostream> 2. 3. using namespace std; 4. 5. class A 6. { 7. int x =5; 8. friend class B; // friend class. 9. }; 10. class B 11. { 12. public: 13. void display(A &a) 14. { 15. cout<<"value of x is : "<<a.x; 16. } 17. };
  • 12. Example of a friend class. 18. int main() 19. { 20. A a; 21. B b; 22. b.display(a); 23. return 0; 24. } Output: value of x is : 5