OOPS Lecture 1 ; Friend class
What is a friend class ?
In C++, afriend classis a class that is given accessto the private and
protected members of another class. This is done by declaring the friend
class inside the definition of the class whose private and protected
members need to be accessed.
Syntax
Declaration:
friend
class
ClassB
;
Usage:
class
ClassB
{
public:
void
display
(
ClassA
&
a) {
// Accessing private members of ClassA
cout
<<
"Private Data from ClassA: "
<<
a
.
privateData
<<
endl
;
}
};
Properties:
Access to Private and Protected Members:
friend class can access private and protected members of the class it is
A
friends with.
Not a Member of the Class:
espite having access to private members, the friend class is not
D
considered a member of the class. It doesn’t need to be instantiated from
the class to access its private members.
Friendship is Not Inherited:
If a class A is a friend of class B, and class B is inherited by class C, then
class C does not automatically become a friend of class A.
Mutual Friendship is Possible:
One class can be a friend of another class, and vice versa.
Difference between friend function and class
Friend Function:
function that is not a member of the class but has access to the private
A
and protected members of the class.
Friend Class:
class that is given access to all the private and protected members of the
A
class it is friends with.
Code:
#include
<iostream>
using
namespace
std
;
class
complex
;
class
calculator
{
public:
complex
sumComplex
(
c
omplex
,
complex
);
};
class
complex
{
private:
int
real
,
imag
;
friend
class
calculator
;
public:
complex
() {}
complex
(
int
real,
int
imag)
{
this
->
real
=
real;
this
->
imag
=
imag;
}
void
display
(){
cout
<<
real
<<
" + "
<<
imag
<<
"i"
<<
endl
;
}
};
complex
calculator
::
sumComplex
(
complex
o1,
complex
o2)
{
complex
o3
;
o3
.
real
=
o1
.
r
eal
+
o2
.
r
eal
;
o3
.
imag
=
o1
.
i
mag
+
o2
.
i
mag
;
o3
.
display
();
return
o3
;
}
int
main
()
{
complex
c1
(
1
,
2),
c2
(
1
,
2);
calculator
c;
c
.
sumComplex
(
c1
,
c2
);
return
0
;
}
class
ClassA
{
private:
int
privateData
;
public:
ClassA
() :
privateData
(
10
) {}
// Friend class declaration
friend
class
ClassB
;
}