what is friend function? explain friend function with example

c++ introdues two new types of the function namely friend function and virtual function.they are basically introduced to handle some spcific task related to class object.we have been emphasizing throught this chapter that the private members can not be accessed  outside  the class .non member function can not have an acess to the private data of a class

To make an outside function “friendly” to class ,we have to simply declare this function as a friend  of the class as shown below

 

Class ABC

{

                        -------------

                        ------------

                        public:

                                    ------------

                                    ------------

                                    friend void xyz(void);

};

 

            the function declaration should be preceded by the keyword  friend.the function is defind  else where in the program like a normal c++ function.the function definition  does not use either the keyword friend or scope operator :: .a friend function although not a member function has full acess right to the private member of the calss.

 

Example.

 

Class test

{

            int t;

            public:

            void get(int a)

{

            t=a;

}

friend void disp(test x)

{

            cout<<x.t;

}

} ;

void main()

{

            test t1 ;

t1.get(10) ;

disp(t1);

}


Average Rating (0)
by Alpa   vatani  in C++  on 9/1/2015 2:42:37 AM  


Post Your Comment
*