0% found this document useful (0 votes)
21 views2 pages

C++ Friend Function Guide

Uploaded by

lysarith09
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views2 pages

C++ Friend Function Guide

Uploaded by

lysarith09
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

C++ Friend Function

Friend Function ក្នុង C++ គឺ៖


- Not a Member of the Class: មិត្តភាពមិនមមនជាសមាជិក្នន Class មែលពាក្់ព័នធន ោះនេ។
- Access to Private and Protected Members: ពួក្វាអាចចូលែំន ើ រការសមាជិក្ Private និង
Protected នន Class។
- Keyword friend: អ្នក្ត្ត្ូវនត្រើ Keyword friend នៅក្នុងការរញ្ជាក្់ Function នៅក្នុង Class។
- Function Definition:
o Function Declaration: នៅក្នុង Class
o Function Definition: នៅនត្ៅការរញ្ជាក្់ Class។
o មិនចំបាច់នត្រើន្មោះ Class និង Operator :: នេ។
- Calling the Function: អ្នក្អាចនៅមិត្តភាពនោយមិនចំបាច់នត្រើ Object នន Class។
Syntax:
1. Declaration inside the class:
class ClassName {
private:
// Private members
public:
friend ReturnType FunctionName(class); // Friend function declaration
};
2. Definition outside the class:
ReturnType FunctionName(class object_parameter) {
// Function body
}
3. Calling Function
FunctionName(object)
Example:
#include<iostream>
using namespace std;
//Friend Function
class Family{
protected:
//Attributes - Properties
string father;
string mother;
private:
string brother;
string sister;
public:
//Function Declaration
//Methods
void set(string,string,string,string);
//Friend Function
//friend return-type FriendFunction(Class-Name);
friend void Friend(Family);
};
//Outside Class Definiton
void Family::set(string Father,string Mother,string Brother,string Sister){
father = Father;//Dara
mother = Mother;//Neary
brother = Brother;//Bona
sister = Sister;//Sophy
}

//Friend Function Definition


void Friend(Family Obj){
cout << "-----------------------" << endl;
cout << "Your Father: " << Obj.father << endl;//Your Father: Dara
cout << "Your Mother: " << Obj.mother << endl;//Your Mother: Neary
cout << "Your Brother: " << Obj.brother << endl;//Your Brother: Bona
cout << "Your Sister: " << Obj.sister << endl;//Your Sisister: Sophy
cout << "-----------------------" << endl;
}

int main(){
//Instance Object
Family Itm;
//Accessing to Method set(...)
Itm.set("Dara","Neary","Bona","Sophy");
//Accessing to Friend Function Friend(...)
Friend(Itm);
return 0;
}
Output:

You might also like