Introduction
In this blog, we will learn about friend function in the C++ language. In object oriented programming language private members cannot access from outside the class. In this situation friend function plays a major role.
What is friend function?
A function that accesses private members of a class but is not itself a member of class is called friend function.
Characteristics of a friend function
- It is not declared as a member of any class.
- It is invoked like a normal function using the friend keyword.
- It can access the private members of a class using the object name.
- It has the objects as arguments.
Example
This example shows how to access private members of a class using the friend function.
-
-
- #include<iostream.h>
- #include<conio.h>
-
- class B;
-
- class A
- {
- private:
- int a;
- public:
- void setData()
- {
- cout<<"Enter 1st number: ";
- cin>>a;
- }
- friend void sum(A ob1,B ob2);
- };
- class B
- {
- private:
- int b;
- public:
- void setData()
- {
- cout<<"Enter 2nd number: ";
- cin>>b;
- }
- friend void sum(A ob1,B ob2);
- };
- void sum(A ob1,B ob2)
- {
- int s=ob1.a+ob2.b;
- cout<<"sum: "<<s<<endl;
- }
-
- void main()
- {
- clrscr();
- A obj1;
- B obj2;
- obj1.setData();
- obj2.setData();
- sum(obj1,obj2);
- getch();
- }
In this blog, I will try to explain how to access private data of a class using the friend function in C++ language. Thanks for reading.