Display Values using Friend Function in C++


This program defines a class XYZ with two private members num and ch, both initialized with specific values. The class also declares a friend function disp which takes an object of class XYZ as its argument.

The disp function is defined outside the class and is able to access the private members of the class XYZ because it has been declared as a friend of the class. In the main function, an object obj of class XYZ is created and passed as an argument to the disp function which then displays the values of the private members of the object.

Source Code

#include <iostream>
using namespace std;
class XYZ
{
  private:
    int num=100;
    char ch='Z';
  public:
    friend void disp(XYZ obj);
};
void disp(XYZ obj)
{
   cout<<obj.num<<endl;
   cout<<obj.ch<<endl;
}
int main()
{
   XYZ obj;
   disp(obj);
   return 0;
}
To download raw file Click Here

Output

Enter Student Name: Ram
100
Z

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