Professional Documents
Culture Documents
C++ Lecture-22
C++ Lecture-22
02
LECTURE 22
04
Today’s Agenda
01 Necessity of Friend Functions
03 A programming Challenge
05 Forward Declaration
06
05 Friend Classes
05
Solution of Assignment Given in last Class
1. The above-given problem can't be solved as the member function of Alpha can't
access the member function of Beta and the vice versa of the above scenario
will also encounter the same problem
2. Now the only solution is that we have to create a friend function which is the
friend of both the classes which will be parametrized and will take the object as
.
a parameter of both the classes so we can access the private data member
inside a single function
A Function Being Friend of 2 Classes
class Beta; }
class Alpha friend void compare(const Alpha &, const Beta &); obj1
{ };
private: void compare(const Alpha & P, const Beta & Q)
int a; This kind of {
a
public: if(P.a > Q.b) 10
void get() statement is cout<<"Greater is "<<P.a<<endl;
{ called Forward else if(Q.b > P.a)
cout<<"Enter a: ";
cin>>a; Declaration
cout<<"Greater is "<<Q.b<<endl;
else
1000
} cout<<"Both are equal"<<endl;
friend void compare(const Alpha &, const Beta &); .
}
}; int main()
class Beta
{
{
Alpha obj1;
obj2
private: Beta obj2;
int b; There declaration obj1.get();
public: obj2.set(); b 20
void set() is important compare(obj1, obj2);
{ return 0;
cout<<"Enter b: "; }
cin>>b; 2000
Forward Declaration
FORWARD DECLARATION
In this, the declaration of a class is given prior to the definition of the class
this is required when class is in use before the definition of class
1. Suppose we have one more class in the above-given example let say Gamma then
we have to declare the function inside the Gamma class, then our code will contain
total 3 classes, and friend function will be declared in 3 places i.e. inside all the
above mentioned 3 classes and the total forward declaration will be 2 i.e for class
Beta and class Gamma
Output:-
Enter a and b: 10 20
Numbers are: 10, 20
The sum is: 30
Thank you