Professional Documents
Culture Documents
22-Friend Functions and Class in C++-19!04!2022 (19-Apr-2022) Material I 19-04-2022 Friend Functions and Class in CPL
22-Friend Functions and Class in C++-19!04!2022 (19-Apr-2022) Material I 19-04-2022 Friend Functions and Class in CPL
// syntax:
//class class_name {
// }
o The function is not in the scope of the class to which it has been declared as a friend.
o It cannot be called using the object as it is not in the scope of that class.
o It can be invoked like a normal function without using the object.
o It cannot access the member names directly and has to use an object name and dot
membership operator with the member name.
o It can be declared either in the private or the public part.
#include <iostream>
class A {
int x;
public:
void setdata(int i)
x = i;
class B {
int y;
public:
void setdata(int i)
y = i;
};
void min(A a, B b)
else
cout<<b.y<<endl;
int main()
A a;
B b;
a.setdata(110);
b.setdata(202);
min(a,b);
return 0;
#include<iostream>
class A {
private:
int a;
public:
A() {
a = 12345;
friend class B;
};
class B {
private:
int b;
public:
void showA(A& x)
};
int main()
A a;
B b;
b.showA(a);
return 0;
// Friend Function
#include<iostream>
class Distance {
private:
int meter;
Distance() : meter(0) {
};
int AddTen(Distance d) {
//friend function
d.meter +=10;
return d.meter;
int main()
Distance D;
return 0;
Output:-
Distance : 10
#include<iostream>
class C_A{
public:
C_A() : numA(12) {
}
private:
int numA;
};
class C_B{
public:
C_B():numB(1) {
private:
int numB;
};
int main()
C_A ObjA;
C_B ObjB;
return 0;
Output:-
Sum : 13
//reusability:-
// Code Reusability