Printing character Interger using friend function in C++


This is a C++ program that demonstrates the use of friend classes to access private data members of a class, XYZ. The program defines a class XYZ with two private data members, a character (ch) and an integer (num), and a friend declaration for the class ABC.

The program also defines a class ABC with a public member function disp, which takes an object of class XYZ as its argument and prints the values of its private data members. In the main function, the program creates an object of class ABC and an object of class XYZ, and calls the disp function of the ABC object, passing the XYZ object as an argument. The disp function of ABC then accesses the private data members of the XYZ object using the friend declaration, and prints their values.

Source Code

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

Output

A
11


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