FRIEND FUNCTION IN C++

SAIROSHNI

Friend Function

A class contains:
👉Public
👉Private
👉Protected members

Public members- Accessed by all
Private members- Accessed by class members only
Protected members-Accessed by class members and its sub class(child class)
        Without changing private mode if anywhere wants to access class members, friend function is an option.

Rules Friend Function Contains:

  1. It is a non-member function.
  2. It can access private, protected member of a class.
  3. Use friend keyword, in front of the function.
  4. Friend function has objects as arguments.
  5. Friend  function should be called directly, without using objects.

Program:

#include<iostream.h>
class frndemo
{
int x,y;
public:
void setvalue()
{
x=10;
y=20;
}
friend void share(frndemo obj);
};
void share(frndemo obj)
{
cout<<\n"<<"x="<<obj.x;
cout<<\n"<<"y="<<obj.y;
}
void main()
{
frndemo obj;
obj.setvalue();
share(obj);
}

Output:

 



Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send