Program To Demonstrate How A Friend Function Acts As A Bridge Between Two Classes Using C++

LEVEL: Beginner

Whats in this post?

  1. Code
  2. Output
  3. Background and Explanation of the code


To copy code: Click View Source “View Source” on the right of this code snippet.

Background and Explanation of the code

The purpose of this program is to calculate the difference of data members of the objects of two different classes.For this, we have defined two classes xxx and yyy having a data member x and y respectively which are initialized through their respective single parameter constructors.In order to compute the difference of the private data members of objects ob1 and ob2 of two classes xxx and yyy respectively, we make a function f1 ( ) which is friend to both the classes.This function is declared as friend in both the classes as

friend  void f1 (xxx, yyy);

This friend declaration has two arguments of class types xxx and yyy.The first declaration of the friend function in class xxx expects that the class yyy is already defined but it is not so.To refer to the name of the class yyy as argument without actually defining it, C++ provides a way know as Forward declaration.The statement

class yyy;

at the beginning of the program is the forward declaration of class yyy which allows us to refer to class yyy without actually defining it.


Difference =  5