- Asked 2/10
- 2070 Asar · 6 marks
- 2069 Chaitra · 6 marks
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)
Related questions
- Time class: add two objects · Object Oriented Programming, chapter 1
- Program using static members · Object Oriented Programming, chapter 4
- Protected specifier; student/test/result program · Object Oriented Programming, chapter 6
- Friend class and encapsulation · Object Oriented Programming, chapter 4
- Consultant's friend supplies material; community objects · Engineering Professional Practice, chapter 7
- 8085 ALP: add two tables, sum and carry · Microprocessor, chapter 2
- Add two matrices · Computer Programming, chapter 7
- Array overflow/underflow; add two arrays · Computer Programming, chapter 7