Object Oriented Programming - Old Questions

11. What is friend function? Write a program to multiply any two private numbers of two different classes using friend function.

5 marks | Asked in 2074

A friend function is a function that can access private members of a class even though it is not a member of that class.

Program:

#include <iostream>

using namespace std;

class XYZ;

class ABC

{

private:

    int value;

public:

ABC()

{

value = 6;

}

friend int multiply(ABC, XYZ); 

};


class XYZ

{

private:

    int value;

public:

XYZ()

{

value = 4;

}

friend int multiply(ABC, XYZ);   

};


int multiply( ABC v1, XYZ v2 )       

{

return (v1.value * v2.value);

}

int main()

{

ABC a;

XYZ x;

cout << "Product of two number is : " << multiply( a, x ) << endl;

return 0;

}