#11-Friend function:Characteristics,Member function of one class as friend of another class,Friend Function as a bridge between 2 classes AND FRIEND CLASS ALSO!

Friend Function

Today we will be learning about the concept of friend function and friend class. So, what is friend function?

Let’s compare this problem with a real life problem. Suppose you need to ask your class mate for water. Then, can you ask it if he is not your friend? Not at all. So, the first way of asking his water is by being his friend.

In the similar manner, the friend function in programming helps to access the things of a friend.

In above case the friend was between human being, but in the case, friendship is between classes.

The concept of encapsulation and datqa hiding in C++, allows only the member function of a class to access the private and protected information of a class.

“Sometimes, there may arise a situation that non-member functions need to access private and protected information of a class.

In such a case, the concept of friend function is used.

 c plus plus program, c++ programming, c++ programming tutorial, c++ tutorial, cplusplus tutorial, solved c++ programs, c++ practical programs, c++ tutorial for engineering, c++ in codeblocks tutorials, c++ online academy,

Characteristics of a friend function-:

  1. It is not within the scope of a class.
  2. The friend function can be declared, either in private or in public section of a class.
  3. Friend function should be declared within a class and should be defined outside of class. And while defining it, the keyword friend is OMITTED. REMEMBER THIS, THAT WHILE DEFINING THE KEYWORD FRIEND IS OMITTED.
  4. Generally, friend functions takes objects as arguments.
  5. It is invoked as a normal function without a help of a object. The friend function is invoked as a normal function, because friend function is not a member function of a class. But, if there is friendship between the functions of one and another class, then there is a need of invoking it with a help of object.
  6. Friend function operates according to the objects passed as an argument.

Now, let’s do a syntax of friend function.

I will not write this in code block, instead I will directly write the syntax on ms word.

Syntax-:

Class class-name

{

Private:

//data members;

Public:

//member functions

Friend return_type fxn_name(objects as argument)

};

Return_type fxn_name(obj as fxn argument)

{

//body of function

}

This tutorial is going to be very big and very important for your exams. So follow this carefully by taking notes in your copy while understanding this blog.

One tip-: These theories/programs are bit long and tedious. Don’t think that these stuffs are not so useful for future jobs/etc. A thinking of someone who is studying C++ should be broad. Though, you may never use this concept in software development, you will still need this concept to understand other people’s codes. Likewise, getting the job is not the expected outcome of studying C++. But, I can guarantee that you will land a good job, if you follow my tutorials from beginning to the end. I am focusing on the end, because that’s going to be the special surprise. And, it won’t take so long. After 2-3 months, we will reach there very easily.

So, let’s start solving a programming problem.

(Q1) Write a program to show the concept of friend function. Add two complex objects of type complex.

The source code is as below.

  • #include<iostream>
  • using namespace std;
  • class complexx
  • {
  •     float real,imag;
  • public:
  • void input()
  • {
  •     cout<<“Enter the real and imaginary parts”;
  •     cin>>real>>imag;
  • }
  • void display()
  • {
  •     cout<<real<<“+i”<<imag;
  • }
  • friend complexx addcomplexx(complexx c1,complexx c2);
  • };
  • complexx addcomplexx(complexx c1,complexx c2)
  • {

complexx temp;

  •     temp.real=c1.real+c2.real;
  •     temp.imag=c1.imag+c2.imag;
  •     return temp;
  • }
  • int main()
  • {
  •     complexx c1;
  •     complexx c2;
  •     c1.input();
  •     c2.input();
  •     complexx c3=addcomplexx(c1,c2);
  •     c1.display();
  •     cout<<“+”;
  •     c2.display();
  •     cout<<“=”;
  •     c3.display();
  •     return 0;
  • }

Its output will come like below.

 c plus plus program, c++ programming, c++ programming tutorial, c++ tutorial, cplusplus tutorial, solved c++ programs, c++ practical programs, c++ tutorial for engineering, c++ in codeblocks tutorials, c++ online academy,

So, let’s explain the working of the above program. We will discuss in brief, about how the program runs.

It all starts with the main function.

At first, we created a complex object c1, then c2. We don’t name the class complex, instead we name complexx because complex is a keyword in code::blocks and we can’t use the keyword as a class name.

After that, we take inputs for c1 and c2.

We do it as c1.input(); and it will take us to the void input function, where we will take the real and imaginary part values.

After that, we take another complex object c3, which will call addcomplexx(objects..) friend function.

I want to repeat the point 5, because I actually mean it. Seriously, if you don’t get that point 5, you won’t get what is going to be explained ahead.

And, I know that you are lazy to go above and look at point 5. So I am pasting it again in italic.

  1. It is invoked as a normal function without a help of a object. The friend function is invoked as a normal function, because friend function is not a member function of a class. But, if there is friendship between the functions of one and another class, then there is a need of invoking it with a help of object.

So, we don’t need to invoke the friend function by object ie c1.input() was done because input() is not a friend function. But, we can’t do, c3.addcomplexx(c1,c2) because as per point 5, this is the case of friend function and without the friendship between two classes. And as we can see that here is only one class, so no two classes, no friendships between two classes, so no need to write c3.addcomplexx. So, alright. And notice the c1,c2 passed. They are objects. And, as per above point number, 4, friend function is taking object as an argument.

After that, we did called the display function using c1 object. Then c2 object also did the same. We did a formatting in such a way that c1+c2 will occur as output. Then we equaled that value with c3.display(). c plus plus program, c++ programming, c++ programming tutorial, c++ tutorial, cplusplus tutorial, solved c++ programs, c++ practical programs, c++ tutorial for engineering, c++ in codeblocks tutorials, c++ online academy,

The above figure clearly explains what I was explaining above.

I don’t hope but guarantee that everything that has been explained till now, is crystal clear. So let’s move ahead towards the next concept of friend function.

Our next case is as below.

Member function of one class as friend function of another class

Sometimes, a member function of one class may need to access the private and protected information of another class.

And, in such cases, the member function of one class is made friend with another class.

And it is done so, by taking another class object as an argument.

There will be new terms on the way, and don’t take tensioned as I will explain all of them on the way. Its source code is given as below.

  1. #include<iostream>
  2. using namespace std;
  3. class Second; //forward declaration
  4. class First
  5. {
  6.     int data1;
  7. public:
  8.     void input()
  9.     {
  10.         cout<<“Enter the value for data”;
  11.         cin>>data1;
  12.     }
  13.     void adddata(Second);
  14. };
  15. class Second
  16. {
  17.     int data2;
  18. public:
  19.     void input()
  20.     {
  21.         cout<<“enter the value for data2”;
  22.         cin>>data2;
  23.     }
  24.     friend void First::adddata(Second S);
  25. };
  26. void First::adddata(Second S)
  27. {
  28.     int X=data1+S.data2;
  29.     cout<<“Sum=”<<X;
  30. }
  31. int main()
  32. {
  33.     First F1;
  34.     Second S1;
  35.     F1.input();
  36.     S1.input();
  37.     F1.adddata(S1);
  38.     return 0;
  39. }

Now, its output will come as below.

 c plus plus program, c++ programming, c++ programming tutorial, c++ tutorial, cplusplus tutorial, solved c++ programs, c++ practical programs, c++ tutorial for engineering, c++ in codeblocks tutorials, c++ online academy,

Now, let’s discuss how the program is being executed inside codeblocks.

It all starts with the int main function. Inside the int main function, we can actually see that, the object of first as F1; and the object of second as S1 was created. And then, F1 invoked the input function as F1.input(), likewise the S1 invoked the input function as S1.input().

Then, inside that input function, we can see that user is being asked to enter the value for data. By F1.input(), we took the input for the First class member F1. Then, after it, we take the input for S1 object of second class. There is no role of friend function, till here. As we can see that we have 2 functions already in the first and second functions.

Now, comes the interesting programming. We will start to execute the friend..

We did F1.adddata(S1), this way, we invoked adddata from F1 and passed S1 inside it.

In the above output example F1=1,S1=1.

The function will firstly go to First class and then enter the declaration of void adddata(Second). And in the place of Second, S1 will be going inside.

Then, we will need to go to class Second. And inside it, we can see that

Friend void First::adddata(Second S) is being done. It is nothing but making the class second as the friend of class first. And here also the S1 will enter inside the argument of Second S.

As soon as we finish that step, the program will come out of the class. and, we can see that; we are defining a function outside of class according to the syntax.

Here also, inside Second S, S1 gets entered.

Finally, we move inside the body of this function. There is a object named x, which will store the sum as data1+s.data2;

As F1=data1 and S1=data2. And S.data2 means that S is being passed as an argument.i.e

 c plus plus program, c++ programming, c++ programming tutorial, c++ tutorial, cplusplus tutorial, solved c++ programs, c++ practical programs, c++ tutorial for engineering, c++ in codeblocks tutorials, c++ online academy,

Remember that: Forward declaration means to declare a class to let the compiler know that that class is to come next. Here as we can see, we have done forward declaration for Second class as, class Second;

Hence, in this way, this program runs!

I hope that till now, each and every concept has been crystal clear.

Some concepts might be hard to grab when seeing this article at first. So, in order to be good, you need to read the same blog again and again, ask questions where you didn’t get. Also, don’t forget to join our facebook page, Thomas Alva Edison, where you canyou’re your programming doubts. So that you can understand it deeply.

Now our next topic is about bridging two classes by the help of friend function.

Friend function as a bridge between two classes

 c plus plus program, c++ programming, c++ programming tutorial, c++ tutorial, cplusplus tutorial, solved c++ programs, c++ practical programs, c++ tutorial for engineering, c++ in codeblocks tutorials, c++ online academy,

So, the above figure shows that to join 2 classes, we used friend function for bridging purpose.

But, that much isn’t enough for you. So I am going to further explain that thing.

Sometimes, a function needs to access or use both the classes, private and protected data members. And in such a case, what we do is that, we declare a common friend function to both the classes by passing both classes objects as argument.

So that function can access or use the private and protected data members of both the classes.

Now, let us see a programming example of it.

The question that we are going to solve is as follows.

Write an example program showing the concept of friend function as a bridge between two classes.

The program source code will be as follows.

  1. #include<iostream>
  2. using namespace std;
  3. class Second;
  4. class First
  5. {
  6. public:
  7.     int data1;
  8. public:
  9.     void input()
  10.     {
  11.         cout<<“Enter the value for data1”;
  12.         cin>>data1;
  13.     }
  14.     void Largest(First,Second);
  15. };
  16. class Second
  17. {
  18. int data2;
  19. public:
  20.     void input()
  21.     {
  22.     cout<<“Enter the values for data2”;
  23.     cin>>data2;
  24.     }
  25.     friend void largest(First,Second);
  26. };
  27. void largest(First F,Second S)
  28. {
  29.     if(F.data1>S.data2)
  30.     {
  31.         cout<<F.data1<<“is largest”;
  32.     }
  33.     else{
  34.         cout<<S.data2<<“is largest”;
  35.     }
  36. }
  37. int main()
  38. {
  39.     First F1;
  40.     Second S1;
  41.     F1.input();
  42.     S1.input();
  43.     largest(F1,S1);
  44.     return 0;
  45. }

And its output will come as below.

 c plus plus program, c++ programming, c++ programming tutorial, c++ tutorial, cplusplus tutorial, solved c++ programs, c++ practical programs, c++ tutorial for engineering, c++ in codeblocks tutorials, c++ online academy,

As you can see that, we entered 2 for data1 and 3 for data2 and saw that 3 was largest, which is correct.

So, let’s discuss what is going inside the above program.

It all starts with the int main function.

Inside the int main function ,we at first created object F1 for first class, then S1 for second class. then, object F1 invoked its input function as F1.input().

This step of the program will lead the user to input function of class first, where it takes value for data1.

Again, same thing will happen for second S1 and it will store data2.

Then the largest function will be called by passing F1 and S1 as arguments in it.

As we can observe in the above program, largest function is on both the classes.

It is on class first as friend void largest(First,Second). Likewise, it is also inside the second class as, friend void largest(First,Second).

Then, let’s have a look at the largest function. We can see that the largest function is inside the class Second. We have passed First F and Second S inside it.

Then, we need to compare if any one of them is the largest. So, for that, we did the following code as shown by figure.

 c plus plus program, c++ programming, c++ programming tutorial, c++ tutorial, cplusplus tutorial, solved c++ programs, c++ practical programs, c++ tutorial for engineering, c++ in codeblocks tutorials, c++ online academy,

So, it will calculate the largest value in this way.

So, we completed a huge topic of programming. That is, we completed the concepts of friend functions. This article has been so long.

I hope you are reading upto here.

I believe that the article was interesting enough to follow until this.

After this let’s discuss about the Friend Class now.

Friend class

Sometimes there may arise a situation that all the member functions of one class needs to be declared as a friend to another.

In such a case, we can declare an entire class as a friend to another class.

So, if member functions of class B needs to be declared as a friend to class A, then we can declare entire class B as a friend to class A, and this is called as friend class method.

So, let’s see how questions can be asked in your examinations, relating to these things we studied till now.

Those who are self taught programmers can google the solutions, likewise ask for help in comment section/facebook page (Thomas Alva Edison).

Questions are as follows.

Q)Why do we need friend function? Explain how the member function of a class can be declared as a friend function of another class with example. (2+6 marks)

Q2) What do you understand by friend function and classes? Explain with example. Write a program to add members of objects of two different classes.2+6

I am not going to solve them. You have to do this. If there are any programs not solved by me(which is rare), then you can first discuss with friends, then your teacher/google; and if nothing works, come to me. Ask in the facebook page or comment section and you will get the answer.

So, we were in friend class. so let’s write a program related to friend class.

The source code for the friend class example is as below.

Its output will come as follows.

So, let’s discuss about the working of this program.

So, everything starts with the int main function.

At the beginning, we have created a F1 object for First Class and S1 object for second class.

F1 then go to access input function.

Whereas, the S1 goes to access the get_data function, by passing F1 as argument.

As input() is declared inside “First” class, we can do F1.input(); whereas, void get_data(First) is declared in second class.

We are willing to pass object of first class into second class to calculate the greatest between the two.

So, for that purpose, we will have to follow a specific syntax, which will follow the form as shown in figure below.

bujhne.png

I hope everything is clear from the above figure.

The program explanation has been completed till now.

If this helped you, don’t forget to share with your friends, share it with everyone.

Stay conscious!

PS-: I have literally used the web application from atlantab to paste the code in first 2 programs. When I pasted it in MS-Word, everything was alright, but when I posted it in wordpress, it has changed!

The code is 100% correct though, but the looks has been changed.

So, I may have to think about that from next time!

 

Share this and have a good day!

Facebook

2 Comments

  1. Hey I know this is off ttopіc but I was wondering if you knew of any wiudgets
    I could add tto my blog tһat automatically tweet
    my newest twitteг updates. I’ve been looking for a
    plug-in like this for quite ome time and was hoing
    maybe yoou would have some experience with something lіkme this.
    Please let me know if you run intօ anythіng. I truly enjoy
    reading youг blog and I look forward to your new updates. https://sablonkaosdistrobandung.blogspot.com/

  2. Hey I know tһis is off topic but I was wоndeгing if you knew ߋf any widgets I coսld adⅾ to my blog that automatically tweet my neweѕt twitter updɑtes.
    I’ve been looking fοr a plug-in like thiѕ for quite skme time and was hoping maybe you would have some eхperience
    with something like this. Please let me know if
    you run into ɑnything. I truly enjoy readіng your blog and I look forwarrd to youг new
    updates. https://sablonkaosdistrobandung.blogspot.com/

Leave a Reply

Your email address will not be published.


*