Printing sum of values using friend function in C++


This is a C++ program that demonstrates the use of friend functions to access private data members of two different classes, A and B. The program defines two classes, A and B, each with a private integer data member (numA and numB, respectively) and a constructor to set the value of the data member.

The program also defines a friend function add, which takes objects of classes A and B as its arguments and adds their private data members (numA and numB, respectively) to find and return the sum.

In the main function, the program creates objects of classes A and B, and calls the add function, passing the objects as arguments. The add function then adds the data members of the objects and returns the sum, which is printed in the main function.

Source Code

#include<iostream>
using namespace std;
class B;
class A
{
  private:
    int numA;
  public:
    A(): numA(12) { }
    friend int add(A, B);
};
class B
{
  private:
    int numB;
  public:
    B(): numB(1) { }
    friend int add(A , B);
};
int add(A objectA, B objectB)
{
  return (objectA.numA + objectB.numB);
}
int main()
{
  A objectA;
  B objectB;
  cout<<"Sum: "<<add(objectA,objectB);
  return 0;
}
To download raw file Click Here

Output

Sum: 13

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