C++ Programming
Friend function in OOP | C++
Definition
A friend function is a non-member function that can access private and protected members of a class.
In C++, a friend function is declared inside a class and defined outside the class.
Friend Function Declaration
The friend function is declared inside the class using the friend keyword.
Syntax:
class ClassName
{
private: // Private members of the class
public: // Friend function declaration friend
void functionName(ClassName & obj);
};
Friend Function Definition
The definition of the friend function is done outside the class.
Syntax:
void functionName(ClassName & obj)
{
// Access private members of the class
cout << obj.privateMember << endl;
}
Example 1: a friend function to input and display the name of someone
#include<iostream>
using namespace std;
class A
{
private:
string name;
public:
friend void inputAndDisplay(A& o);
};
void inputAndDisplay(A& o)
{
cout<<“enter your name: “;
cin>>o.name;
cout<<“Your name is “<<o.name;
}
int main()
{
A a;
inputAndDisplay(a);
return 0;
}
Example 2: a public function to input name of someone and a friend function to display that name
#include<iostream>
using namespace std;
class A
{
private:
string name;
public:
void input()
{
cout<<“enter your name: “;
cin>>name;
}
friend void display(A& o);
};
void display(A& o)
{
cout<<“Your name is “<<o.name;
}
int main()
{
A a;
a.input();
display(a);
return 0;
}
Example 3: two friend functions (one to input name and other to display that name)
#include<iostream>
using namespace std;
class A
{
private:
string name;
public:
friend void input(A & o);
friend void display(A & o);
};
void input(A & o)
{
cout<<“Enter your name: “;
cin>>o.name;}
void display(A & o)
{
cout<<“Your name is “<<o.name;
}
int main()
{
A a;
input(a);
display(a);
return 0;
}
ALL S3 Chemistry National Exams & Marking Schemes (NESA) – Download Now!
Imyanya 310 yo kuba DASSO | Umujyi wa Kigali | Ntucikwe n’aya mahirwe
Important notice
⚠️ All Jobs and Opportunities published on fdo.net.rw are completely free to apply.
Never pay any fee during the recruitment process!
Even if fdo.net.rw does its best to avoid scam job or opportunity offers, job seekers or opportunity seekers are 100% responsible for applying at their own risk.
Check carefully before applying. If you doubt the legitimacy of any offer, do not apply and contact us at
freedigopp54@gmail.com
Never pay to get a job or opportunity - if you do, you do so at your own risk.
