0% found this document useful (0 votes)
8 views9 pages

A5-Friend Functions and Friend Classes

The document discusses friend functions and friend classes in object-oriented programming, emphasizing their role in relaxing access specifiers to allow direct access to class members. It outlines the objectives of a lab experiment aimed at understanding and implementing these concepts, along with practical coding tasks. Additionally, it addresses the controversy surrounding friend functions and classes in relation to encapsulation and data hiding principles of OOP.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views9 pages

A5-Friend Functions and Friend Classes

The document discusses friend functions and friend classes in object-oriented programming, emphasizing their role in relaxing access specifiers to allow direct access to class members. It outlines the objectives of a lab experiment aimed at understanding and implementing these concepts, along with practical coding tasks. Additionally, it addresses the controversy surrounding friend functions and classes in relation to encapsulation and data hiding principles of OOP.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Object Oriented Programming

Friend Functions and Friend Classes


Friend Functions and Friend Classes

Friend Functions and Friend Classes


1. Introduction
In object oriented programming one of the basic goals was to enforce encapsulation and data hiding. This is a feature
that ensures that class members are not accessible openly. We want to provide access to class members through a
regulated mechanism in which all accesses are accountable and legal.
Friend functions and friend classes provide a technique through which you can relax the access specifiers and provide
direct access. Although this seems an attractive technique but it is not liked by hardcore programmers because of its
over relaxing attitude. The concept of friend functions is still important because they need to be used in operator
overloading which will be practiced in the next lab. Hence this lab attempts to build new concepts which will be used
in the next lab.

Relevant Lecture Material

• Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore


o Pages: 468-475

2. Objective of the Experiment


After completing this lab the student should be able to:
• Understand the difference between a regular function and a friend function
• Explain the concept of a friend function.
• Develop a friend function.
• Explain the concept of a friend class.
• Develop a friend class.

3. Concept Map

3.1. Friend Functions

Before going to the syntax of friend functions it is important that we highlight why they are needed. Friend functions
provide a relaxing mechanism through which we can access the private data members of a class directly without any
question being asked. This does not mean that we have relaxed the access specifiers. A friend function provides access
to the private and public data members of a class from only within its body. Friend functions are needed because
sometimes if we have multiple classes and we want to manipulate the class members through a single function.

Another similar scenario is when we want a regular function (that is not member of a class) to access private members
of a class. The final scenario is the use of friend functions in operator overloading (will be discussed in operator
overloading lecture).

Always remember that friend functions are not members of a class they are just regular functions with special
privileges. In order to make a friend function you have to specify that a particular function is a friend function. This
can be achieved through the following syntax:

Page 36
Friend Functions and Friend Classes

class second; //Forward Declaration


class first

private:
int member1;
int membern;
public:
friend void fun( first , second ); //Friend function prototype
};

class second

private:
int mem1;
int mem2;
public:
friend void fun( first, second ); //Friend function prototype
};

void fun( first o1, second o2) //Note that friend is not written

cout<<o2.mem1<<o2.mem2;

void main( )

first obj1;
second obj2;
fun( obj1,obj2); //Simple calling. Cannot use the dot operator

In the syntax above it must be understood that access specifiers are not applicable on friend functions i.e. whether you
write the function in public or private it has no effect. Another important thing to always remember is that it is
compulsory to write the keyword friend with the function prototype but writing the friend keyword in the function
definition will result in a syntax error. In the above code the friend function is bridge between two classes using a
single function. Creating this environment is purely the programmers choice. It is not necessary that you have a
function working like a bridge. You can always have a single friend function inside a single class.

When discussing friend functions one must remember that friend functions are never part of a class. They are written
in the class to show that they have a friendship with the class. Friend functions are not called using the dot notation or
by using the scope resolution. Friend functions are called like a conventional function. Now when using the friend
function we can access both public and private data members directly as if there is no such thing as an access specifier.
An important note regarding friend functions is that these functions should not be used to relax the access specifiers.
Secondly the friendship of a function is one sided i.e. the function can access the class members but the class cannot
access deceleration that are made inside the function.

Page 37
Friend Functions and Friend Classes

3.2. Friend Classes


A friend function has access to those classes with which it is friend. Sometimes a situation arises when we want to
make two classes friends with each other. This means that a class can access the public and private members of
another class directly. To achieve this you must right the friend class statement in the befriending class.

class first

private:
friend class second; //Declaration of friend class
int member1;
int membern;
public:
first()

member1=10;
member2=20;

};

class second

private:
int mem1;
int mem2;
public:
void fun( first o1) //Friend function prototype

cout<<mem1<<mem2;

};

void main( )

first obj1;
second obj2;
obj2.fun( obj1); //cannot call using obj1! Obj1 does not contain a
function called fun

4. Home Work Before Lab


Provided below is a descriptive problem. Your task is to read the question carefully then research the claims and
submit the answer to your lab instructor.

4.1. Practices from Home


Many programmers argue that friend functions and friend classes are against the ideology of OOP. Explain why they
think this is the fact. What qualities of OOP are affected by friend functions and friend classes. Explain in detail and
submit your written work to the lab instructor. There is no need to write any code for this task.

Page 38
Friend Functions and Friend Classes

5. Procedure & Tools

5.1. Tools
Visual Studio 2012.

5.2. Setting-up Visual Studio 2012


Setup Visual Studio and make a project named “series”.

5.3. Walkthrough Task


Find the sum of 𝑎1 + 𝑎2 + 𝑎3 + ⋯+ 𝑎𝑛 arithmetic series. In an arithmetic series the difference between two consecutive
numbers is the same throughout the series. Your class is composed of four data members i.e. the first entry of the
series, last entry of the series, total number of entries for which sum is required and finally the sum up to
𝑛
n terms which has the formula Use a friend function to compute the sum of the series.

5.4. Writing Code


In the source file created in the project “series” write the following C++ code:

class series

friend class sum; //Friend class declaration


int first; //First number
int nterm; //Last number
int entries; //Total number of entries
int sumn; //Sum up till n terms

public:
series(int f, int n, int e)

first=f;
nterm=n;

friend void display(series); //Simple friend function


};

class sum

public:
void series_sum(series &obj)

};

void display(series obj) //Friend Function body

cout<<"The sum of series is "<<obj.sumn<<endl;

Page 39
Friend Functions and Friend Classes

int main()
{
series obj1(6,96,31); //(first term, last term, total number of terms)
sum obj2;
obj2.series_sum(obj1);
display(obj1); //Call the friend function
system ("pause");
return 0;
}

Figure 1: The series class and the sum friend class. The display function is a friend function.

5.5. Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any errors and warnings
that are present in your code.

5.6. Executing the Program


A sample output after running the program is shown below. Also run the code with other possible inputs.

Figure 2: Final output of series project

6. Practice Tasks

6.1. Practice Task 1


As you know in mathematics the quadratic equation is a very popular 2 nd degree equation. Although there are many
possible methods of solving the quadratic equation, a very popular method is through the use of quadratic formula.
The quadratic equation is and its roots can be determined using the quadratic formula as follows:

Your task is to create a class named equation which will have the data members a, b and c which are the coefficients
of the quadratic equation. The class will have two more data members namely proot and nroot which stand for the
positive root and negative root of the equation. Suppose that variables a, b and c are integers. Where proot and nroot
Page 40
Friend Functions and Friend Classes

are floats.

Page 41
Friend Functions and Friend Classes
• Construct the class objects by using a nullary constructor.
• Then design a friend function which will determine the proot and nroot of the equation.
• Create another friend function which will display the values of proot and nroot.

6.2. Practice Task 2


Your task is to create two classes namely number and computation. The computation class is a friend of the number
class.
The number class will be composed of three floating point data members namely a, b and c. The class will also be
composed of a friend function display that can display all the data members.
The computation class is responsible for performing operations on the number class and hence it has three functions
as follows:
• A function to compute the square of sums i.e.
• A function to compute the square of difference i.e.
• A function to compute the mean of the three numbers

6.3. Practice Task 3


Create a class called matrix that will find the sum of two matrices. To perform this task you will need to create three
private array data members that will hold the original arrays and an array to hold the sum of the matrices.
Suppose that the size of the matrices is 3x3.
Create a friend function which will add the matrices and store the result in the sum matrix. The sum of two matrices
is the sum of corresponding entries.

6.4. Outcomes
After completing this lab, students will be able explain the difference between a member function and a friend
function. The students will be able to create friend functions and friend classes. Further they will be comfortable with
the manipulation of objects using both friend functions and classes.

6.5. Testing
Test Cases for Practice Task-1
Sample Inputs Sample Outputs
a =1; proot= 1
b =2; nroot = -3
c =-3

Test Cases for Practice Task-2


Sample Inputs Sample Outputs
a=1
b=2
c=3

Page 42
Friend Functions and Friend Classes

Test Cases for Practice Task-3


Sample Inputs Sample Outputs
Create the following entries for 3x3 arrays Results should be as follows.

7. Further Reading

7.1. Books
• Object-Oriented Programming Using C++, Fourth edition, Joyce Farrell

7.2. Slides
• The slides and reading material will be provided by course instructor.

Page 43

You might also like