मराठी
महाराष्ट्र राज्य शिक्षण मंडळएचएससी विज्ञान (संगणक विज्ञान) इयत्ता १२ वी

Explain friend function in C++ with example. - Computer Science 1

Advertisements
Advertisements

प्रश्न

Explain friend function in C++ with example.

कोड लेखन
स्पष्ट करा
Advertisements

उत्तर

  1. C++ allows a function to be declared as a friend of one or more classes, giving it access to the private data of those classes. Such a function does not have to be a member of any class.
  2. Normally, a non-member function cannot access the private data of a class. However, when two or more classes need to share a common function, a friend function is used.
  3. To make an external function a friend of a class, it is declared inside the class definition as shown below:
    class class-name
    {
    private:
    ......
    ......
    public:
    ......
    friend return-type function-name (arguments); //declaration
    };
  4. The keyword friend specifies that the function has special access to the class. The function itself is defined like a normal C++ function and does not use the class name, the friend keyword, or the scope resolution operator in its definition.

Example:

//Swapping private data of classes using friend function
#include<iostream.h>
#include<conio.h>
class A; //forward declaration
class B
{
    private:
    int val2;
    public:
       void getdata (void)
       {
       val2=21;
    )
    void display (void)
       {
       cout<<“Value 2:"<<val2;
       }
    friend void exchange (B&, A&);
    };
class A
{
    private: 
    int val1;
    public:
    void get (void)
    { 
    val1=12; 
    }
    void disp (void) 
       {
       cout<<"Value 1:"<<val1; 
       } 
       friend void exchange (B&, A&); 
    };
    void exchange (B &x, A &y) 
       { 
           int temp; 
           temp = x.val2;
           x.val2 = y.val1
           y.val1 = temp; 
       }
    void main() 
    {
       A abc;
       Bpqr; 
       abe.get(); 
       par.getdata(); 
       cout<<"Before exchange:-"; 
       abc.disp(); 
       pqr.display(); 
       exchange (pqr, abc); //Swapping 
       cout<<"\n After exchange:"; 
       abc.disp();
       pqr.display( ); 
}
shaalaa.com
  या प्रश्नात किंवा उत्तरात काही त्रुटी आहे का?

APPEARS IN

Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×