Practice File 06
Practice File 06
Spring 2024
Issue Date: March 23, 2024
LAB-06
Friend Functions:
A friend function in C++ is a function that is declared outside a class but is capable of accessing the
private and protected members of the class. There could be situations in programming where we want
two classes to share their members. These members may be data members, class functions or function
templates. In such cases, we make the desired function, a friend to both these classes which will allow
accessing private and protected data of members of the class.
Generally, non-member functions cannot access the private members of a particular class. Once
declared as a friend function, the function is able to access the private and the protected members of
these classes.
Example:
The picture code below shows the declaration, definition and working of friend function
Output:
Output:
Explanation:
In this program, Class A and Class B have declared add( ) as a friend function. Thus, this function can
access private data of both classes. One thing to notice here is the friend function inside Class A is using
the Class B. However, we haven 't defined Class B at this point. For this to work, we need a forward
declaration of Class B in our program (This point is also discussed in comments).
Friend Classes:
A friend class can access private and protected members of other classes in which it is declared as a
friend. It is sometimes useful to allow a particular class to access private and protected members of other
classes.
Example:
Earlier we discussed how a friend function of a class can access its members. If we make the whole class
(ClassB) a friend of other class (ClassA). Now any function of ClassB will have access to all the
members.
Output:
Since ClassB is a friend class, we can access members of ClassA in ClassB by making an object of
ClassA in ClassB. For accessing we don’t have to use getters and setters we can directly access private
members because of the friend relation between two.
Practice Tasks
Do All the Tasks in Multi Files.
Task 1: (20 Marks)
Write a program in C++ to Check Whether a Number can be Express as Sum of Two Prime
Numbers using the friend function. Make a class named as Prime. It’ll contain a Private
member Function bool isPrime(int n).
bool isSumOfTwoPrimes(int n) is a friend function to this class. It’ll use private member
Function isPrime() of the Prime class to check whether the given number is sum of 2 prime
numbers or not.
You have to use your own knowledge to implement a class and a friend function to that class.
Pictorial Representation:
Here is the formula to calculate distance between Centers of both the circles
double distance = sqrt (pow ((X2 – X1), 2) + pow ((Y2 - Y1), 2));
For sqrt and pow You can use cmath library.
Submit a zip folder named as YourRollNo_PracticeFile_06.zip containing all .cpp, .h files on Google
classroom.