Friend Function in C++ Programming


A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions.

  • The program starts by including the necessary header files and defining a class A. The class A has two private data members x and y. In addition, the class has a friend function setData() which is declared using the friend keyword. The friend keyword allows the function setData() to access the private data members of class A.
  • The function setData() is defined outside the class and is used to set the values of x and y to 10 and 20 respectively, using an object of class A. The values of x and y are then printed to the console.
  • In the main() function, setData() is called, which creates an object o of class A, sets its private data members x and y, and prints their values to the console.
  • Since setData() is a friend function of class A, it has access to its private data members and can manipulate them. The use of friend function allows external functions to access and modify the private data members of a class, which can be useful in certain situations where encapsulation needs to be bypassed.
  • The program ends by returning 0 from the main() function, indicating that the program ran successfully.

Source Code

#include<iostream>
using namespace std;
//Friend Function
class A
{
private:
    int x,y;
public:
    friend void setData();
 
};
 
void setData()
{
        A o;
        o.x=10;
        o.y=20;
        cout<<"X : "<<o.x<<endl;
        cout<<"Y : "<<o.y<<endl;
}
int main()
{
 
    setData();
    return 0;
}
 
 

Output

X : 10
Y : 20
To download raw file Click Here

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples