How to add members of two different classes in C++

Add members of two different classes in C++

The friend function in object-oriented programming (OOP) can access all the public, private, and protected members of a class. It is a non-member function of a class. We use the friend reserved word to make a friend function.

Note: We can learn more about the friend function here.

Syntax

The syntax of the friend function is as follows:

class A
{
friend data_type funtion_name (parameters);
};
data_type function_name (parameters)
{
}

We can declare the function anywhere in the class.

Note: There is no friend function in Java.

Code example

Let’s declare all the classes we want to use in the friend function beforehand. The required code is as follows:

#include<iostream>
using namespace std;
class B;
class A
{
int a1 = 9;
public:
friend int add(A, B);
};
class B
{
int b1 = 10;
public:
friend int add(A, B);
};
int add(A a, B b)
{
return a.a1 + b.b1;
}
int main()
{
A object1; // Object of class A
B object2; // Object of class B
cout << add(object1, object2);
return 0;
}

Explanation

  • Line 4: We declare class B. (This is a good approach to declare all classes and functions before defining them).
  • Line 7: We declare a private data member a1 in class A. We initiate it with a value of 9.
  • Line 9: We declare the friend function by using the friend reserved word.
  • Line 14: We declare a private data member b1 in class B. We initiate it with a value of 10.
  • Line 20–23: The friend function add is defined here. We define the friend function like any other function, except for one difference. Unlike with other data types of the parameter, we name the classes where we declare the `friend` function.
  • Line 27: We create an object of class A named object1.
  • Line 28: We create an object of class B named object2.
  • Line 29: We call the friend function and pass both the objects as parameters. Meanwhile, the cout statement displays the answer on the screen.

Conclusion

  • If we overuse the friend function, we lose the purpose of the encapsulation.
  • We need to define the friend function outside the class.
  • A friend function can use any class member we declare it in.

Free Resources