Friend Functions in C++
Submitted by moazkhan on Monday, August 4, 2014 - 08:47.
Friend functions in C++
In this tutorial you will learn: 1. What are friend functions? 2. Why to use friend functions? 3. How to use friend function in a program? 4. Basic C++ syntax What are friend functions? Friend functions are those functions which can access the private as well as the protected data members of the classes. We can make a function friend of two classes so that this function can use the private and protected member of those classes to produce a specific result. We can also make two classes friends of each other. Why use friend functions? We use friend functions and classes whenever we need to access the protected and private members of the classes. Through friend functions we can directly access the private and protected members of a class, it is different by inheritance in a way that by using inheritance we can access the private members only using the member functions of the class. How to use friend functions? We make a function the friend function of a class by writing the keyword “friend” before the function which is called in some class. The example is as follow:- Simple function:
- Class myClass
- {
- int myfunc( );
- //other content of the class written here
- }
- Friend function:
- Class myClass
- {
- friend int myfunc( ); //here friend keyword us added
- //other content of the class written here
- }
- #include<iostream>
- #include<conio.h>
- using namespace std;
- class ClassB; //compiler is told here that we will be having another class as friend fn is called in //ClassA
- class ClassA {
- private:
- int data;
- public:
- ClassA(): data(3) {}
- ClassA(int x)
- {
- data=x;
- }
- friend int friendfun(ClassA, ClassB);
- };
- class ClassB
- {
- private:
- int data;
- public:
- ClassB(): data(7) {}
- ClassB(int x)
- {
- data=x;
- }
- friend int friendfun(ClassA, ClassB);
- };
- int friendfun (ClassA a, ClassB b)
- {
- return (a.data+b.data);
- }
- int main()
- {
- int x,y;
- cout<<"Please input the data(int) of the first class:\n";
- cin>>x;
- cout<<"Please input the data(int) of the second class:\n";
- cin>>y;
- ClassA a(x);
- ClassB b(y);
- cout<<"The result after addtion using friend function is:"<<friendfun(a, b)<<endl;
- return 0;
- }
Add new comment
- 91 views