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.
#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
Sum: 13
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions