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
friendfunction 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
friendfunction 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 AB object2; // Object of class Bcout << 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
a1inclass A. We initiate it with a value of 9. - Line 9: We declare the
friendfunction by using thefriendreserved word. - Line 14: We declare a private data member
b1inclass B. We initiate it with a value of 10. - Line 20–23: The friend function
addis defined here. We define thefriendfunction 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 Anamedobject1. - Line 28: We create an object of
class Bnamedobject2. - Line 29: We call the
friendfunction and pass both the objects as parameters. Meanwhile, thecoutstatement displays the answer on the screen.
Conclusion
- If we overuse the
friendfunction, we lose the purpose of the encapsulation. - We need to define the
friendfunction outside the class. - A
friendfunction can use any class member we declare it in.