Skip to main content

Add objects of two different classes

Short answer

A friend function, declared with the keyword friend, can access private members of the class granting friendship. A friend class grants all its member functions access to another class's private members. To add members of objects of two classes, declare a friend function that takes objects of both classes and returns the sum of their private fields.

What do you understand by friend functions and classes? Explain with example. Write a program to add members of objects of two different classes.

Friend function

A friend function is a non-member function declared inside a class with the keyword friend; it can access the private and protected members of that class. It is not called through an object and has no this pointer.

Friend class

A friend class is a class whose member functions can all access the private and protected members of another class. It is declared in the other class as friend class ClassName;. Friendship is not mutual and not inherited.

class A
{
    int secret;
    friend class B;          // all members of B can access secret
};
class B
{
public:
    void show(A &a) { cout << a.secret; }
};

Program: add members of objects of two different classes

#include <iostream>
using namespace std;

class Second;                        // forward declaration

class First
{
    int a;
public:
    void read() { cout << "Enter value for First: "; cin >> a; }
    friend int add(First, Second);   // friend declaration
};

class Second
{
    int b;
public:
    void read() { cout << "Enter value for Second: "; cin >> b; }
    friend int add(First, Second);
};

int add(First f, Second s)           // defined outside, no scope operator
{
    return f.a + s.b;                // access private members of both
}

int main()
{
    First f;
    Second s;
    f.read();
    s.read();
    cout << "Sum = " << add(f, s) << endl;
    return 0;
}

Sample output

Enter value for First: 12
Enter value for Second: 8
Sum = 20

The forward declaration class Second; is needed because First uses Second in the friend prototype before Second is defined.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 4 questions →