Advertisement

Friend Classes in C++ ( Multiple classes ) | Mohd Abuzar

 




Friend Classes  :  As you are all know that friend function can access the private  and protected data which is declare as a friend . It is sometime to useful the particular classes to access the private member of another class .




Friend Function :  Like a friend class , friend function can be access the grant to access the private and protected data member . It is same as a friend function .

a ) A member of another class

b) A global function 


In a program , we are all know that we can't access the private and protected data member so in c++ friend function is a type of function which can access the private and protected data member and the friend function make the outside the class . But friend function is not same as inheritance .


Example of Friend Classes 


A complete C++ program to demonstrate friend function of another class .


#include <iostream>
class A { private:
    int a;
public:
   A() { a = 0; }
    friend class B; // Friend Class };
class
B {
private:
    int b;
public:
    void showA(A& x)
    { // Since B is friend of A, it can access
 // private members of A
 std::cout << "A::a=" << x.a;
    } };
int main()
{
A a ;
    B b;
    b.showA(a);
    return 0;
}


   Output : 

      A::a=0

 



    A complete C++ program to demonstrate global function .


#include <iostream>
 
class A {
  int a;
public:
  A() { a = 0; }
  // global friend function
friend void showA(A&); };
void showA(A& x)
{
// Since showA() is a friend, it can access
 // private members of A
  std::cout << "A::a=" << x.a;
}
int main()
{
    A a;
 showA(a);
return 0; }


  Output : 

      A::a=0



References : 




Please write comment if you find anything incorrect in the above information .


This article is contributed by Mohd Abuzar . If you like code with abuzar  or want to share more information about this topic so you will be mail at abuzar.abuzar.mohd325@gmail.com 



RECOMMENDED ARTICLES 


 

  












Post a Comment

0 Comments