Private and Protected Example using friend function in C++


This is a C++ program that demonstrates the use of friend classes to access private data members of another class. The program defines two classes, A and B. Class A has a private integer data member x initialized to 5, and class B is declared as a friend of class A. The program also defines a member function display in class B, which takes an object of class A as its argument and prints the value of its private data member x.

In the main function, the program creates an object of classA and an object of class B. The display function of class B is then called, passing the object of class A as an argument. The display function then accesses the private data member x of the object of class A using the friend declaration, and prints its value in the console.

Source Code

#include<iostream>
using namespace std;
class A
{
   int x =5;
   friend class B;
};
class B
{
  public:
    void display(A &a)
    {
       cout<<"value of x is : "<<a.x;
    }
};
int main()
{
  A a;
  B b;
  b.display(a);
  return 0;
}
To download raw file Click Here

Output

value of x is : 5

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