Skip to main content

Friend Functions

CPP09 - W1 - M8: Friend Functions


Learning Objectives

At the end of this module, you will able to:
  • Explain and use friend functions in C++ programs
  • Implement software objects as friends to one another

Introduction


Friend

The concepts of encapsulation and data hiding dictate that nonmember functions should not be able to access an object’s private or protected data. The policy is, if you’re not a member, you can’t get in. However, there are situations where such rigid discrimination leads to considerable inconvenience. in order to access the non-public members of a class, C++ provides the friend facility.
The accessibility of class members in various forms is shown in the below figure
friends.jpg

Friend Functions

Imagine that you want a function to operate on objects of two different classes. Perhaps the function will take objects of the two classes as arguments, and operate on their private data. In this situation there’s nothing like a friend function. Here’s a simple example, FRIEND, that shows how friend functions can act as a bridge between two classes:
// friend.cpp
// friend functions
#include 
using namespace std;
////////////////////////////////////////////////////////////////
class beta; //needed for frifunc declaration
class alpha
{
private:
int data;
public:
alpha() : data(3) { } //no-arg constructor
friend int frifunc(alpha, beta); //friend function
};
////////////////////////////////////////////////////////////////
class beta
{
private:
int data;
public:
beta() : data(7) { } //no-arg constructor
friend int frifunc(alpha, beta); //friend function
};
////////////////////////////////////////////////////////////////
int frifunc(alpha a, beta b) //function definition
{
return( a.data + b.data );
}
//--------------------------------------------------------------
int main()
{
alpha aa;
beta bb;
cout << frifunc(aa, bb) << endl; //call the function
return 0;
}
In this program, the two classes are alpha and beta. The constructors in these classes initialize their single data items to fixed values (3 in alpha and 7 in beta).
We want the function frifunc() to have access to both of these private data members, so we make it a friend function. It’s declared with the friend keyword in both classes:
friend int frifunc(alpha, beta);
This declaration can be placed anywhere in the class; it doesn’t matter whether it goes in the public or the private section.
An object of each class is passed as an argument to the function frifunc(), and it accesses the private data member of both classes through these arguments. The function doesn’t do much: It adds the data items and returns the sum. The main() program calls this function and prints the result.
A minor point: Remember that a class can’t be referred to until it has been declared. Class beta is referred to in the declaration of the function frifunc() in class alpha, so beta must be declared before alpha. Hence the declaration class beta; at the beginning of the program.


Friend Classes

The member functions of a class can all be made friends at the same time when you make the entire class a friend. The program FRICLASS shows how this looks.
// friclass.cpp
// friend classes
#include 
using namespace std;
////////////////////////////////////////////////////////////////
class alpha
{
private:
int data1;
public:
alpha() : data1(99) { } //constructor
friend class beta; //beta is a friend class
};
////////////////////////////////////////////////////////////////
class beta
{ //all member functions can
public: //access private alpha data
void func1(alpha a) { cout << “\ndata1=<< a.data1; }
void func2(alpha a) { cout << “\ndata1=<< a.data1; }
};
////////////////////////////////////////////////////////////////
int main()
{
alpha a;
beta b;
b.func1(a);
b.func2(a);
cout << endl;
return 0;
}
In class alpha the entire class beta is proclaimed a friend. Now all the member functions of beta can access the private data of alpha (in this program, the single data item data1). Note that in the friend declaration we specify that beta is a class using the class keyword:
friend class beta;
We could have also declared beta to be a class before the alpha class specifier, as in previous examples
class beta;
and then, within alpha, referred to beta without the class keyword:
friend beta;


Resources





http://xoax.net/comp/cpp/console/Lesson9.php

Steps to solve the problems sets

  • Read the introduction part of this module
  • View the video and read the supporting material
  • Think about how to write the tic tac toe program with objects.
Spend atleast 1 hour on the resources and Other modules covered so far.


Problem Sets


Problem Set A

1. Game Program: The object of tic-tac-toe is to get three X’s or three O’s in a row either horizontally, vertically or diagonally. The tic-tac-toe game board is a 3 x 3 grid and looks something like this:
board.jpg
During a typical game, players takes turns placing their X’s and O’s on the game board. The first to get their pattern in a row wins. The follow game board represents what the results of a typical game might look like:
board_players.jpg
Use a 3 x 3 array of cell objects to track player turns. Check the array after each player’s turn to see if they’ve won. Draw the game board on the screen after each turn so players can see the game’s progress. Make it a two player game.
Use Object Oriented Programming approach to solve this problem, thought the problem can be solved simple as presented in the video given.
Write a game program called tic-tac-toe by Identifying the Game as a class consists of Player Objects and Board Object. Board consists of Cell Objects representing the cell in the board.
Identify the Objects in the game with attributes and behavior.
Player can have player Name as an attribute and behavior as playing the game.
Identify and the write friend functions\classes in the board class, cell class, player class and Game class.
Use your imagination to identify the objects, It's not limited to the classes which we have defined.
Name the program as:- PA1_TicTacToe.cpp

Comments

Popular posts from this blog

Mini Project - Railway Reservation System

Module 1 Overview Railway Reservation System-(RRS) Project is developed to help students learn and realize capability of C programming language, and appreciate procedural approach of developing a system. RRS helps users reserve/cancel berths, search for trains, check reservation/cancellation history, etc... On the other hand it helps the railway reservation officers to prepare reservation charts, organize train schedules, etc... RRS provides two types of log-ins one is the User log-in for railway customers and the other one is Admin log-in for railway reservation officers. Project is divided into 10 modules of four hours duration each. All the modules will give exactly what to develop in the 4 hour time frame. Since most of the modules are inter-related it is important to keep track of the previous code. After submission it is allowed to make changes in the previous code to suit / integrate well to the system. Before we start the project, we need to make the followin...

Inheritance

Week 1 - M5 : Inheritance Learning Objectives At the end of this module, you will be able to Understand the implementation of inheritance in C++ Override the base class members Access overridden base class members using the scope resolution operator Understand the concept of base class initialization Introduction Inheritance The philosophy behind inheritance is to portray things as they exist in the real world. As inheritance is found in real world, it is important feature of OO programming. Inheritance has many advantages, the most important of them being the resuability of code. Once a class is defined and debugged, it can be used to create new subclasses. The reuse of existing class saves time and effort. The Class from which another class is derived is called the base class . The class which inherits the properties of the base class is called the derived class . Each instance of the derived class includes all the members of the base class. Since...