Change Private Values Using Friend Class in C++ Programming


The given C++ program demonstrates the use of friend function in a class for setting the value of a private data member.

  • The program starts by including the necessary header files and defining a class A. The class A has a private data member x, which is initialized to 0 in the constructor. The class A also has a member function print(), which prints the value of x to the console.
  • The setValue() function is a friend function of class A and takes an object o of class A and an integer a as parameters. The function sets the value of x of the object o to the value of a. Since the setValue() function is a friend function of class A, it has access to its private data member x.
  • In the main() function, an object o of class A is created, and its print() function is called to display the initial value of x. The setValue() function is then called with the object o and an integer value of 25 as arguments to set the value of x to 25. Finally, the print() function is called again to display the new value of x.
  • 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;
public:
    A()
    {
        x=0;
    }
    void print()
    {
        cout<<"X : "<<x<<endl;
    }
    friend void setValue(A &o,int a);
};
 
void setValue(A &o,int a)
{
    o.x=a;
}
 
int main()
{
    A o;
    o.print();
    setValue(o,25);
    o.print();
    return 0;
}
 

Output

X : 0
X : 25
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