Object Oriented Programming
Friend Functions
1
Objectives
• “this” operator
• Friend Functions
• Friend Classes
2
“this” Operator in Class
• Every object in C++ has access to its own address
through an important pointer called this operator /
pointer.
• Alternatively we can say that, with this operator we
can access the objects own members (Methods &
Variables)
o Syntax: Arrow operator (Usually used with pointer)
• this member_Variable;
• this member_method(parameter);
3
Example “this” Operator
class Box{
double width, height, length;
public:
Box(double width, double height, double length);
bool equal(Box b);
};
4
Example “this” Operator
//Constructor of class Box
Box::Box(double width, double height, double length){
//this pointing to the variable of the object of the class
this width = width;
this height = height;
this length = length;
}
//equal method of Box class
bool Box:: equal(Box b){
if(this width == b.width &&
this height == b.height &&
this length == b.length) return true;
else return false;
}
5
Friend Functions of Classes
• A friend function is not the actual member function of
the class
But
• Friend function can even access the private members
of a class.
How? We will see it a bit latter
6
Friend Functions of Classes
• A friend function may or may not be a member of
another class.
• Friend function can be just like a normal function of
any C / C++ program.
• Keyword: simply use the friend keyword in front of
the prototype of the function you wish to be a friend
of the class.
• It doesn’t matter whether you declare the friend
function in the private or public section of the class.
7
Friend Functions (Example)
class Accumulator{
private:
int mValue;
public:
Accumulator() { mValue = 0; }
void Add(int nValue) { mValue += nValue; }
// Make the Reset() function a friend of this class
friend void Reset(Accumulator &cAccumulator);
int getAccumulator() { return mValue; }
};
// Reset() is now a friend of the Accumulator class
void Reset(Accumulator &cAccumulator){
// And can access the private data of Accumulator objects
cAccumulator.mValue = 0;
}
8
Friend Functions (Example)
int main(){
Accumulator ax;
ax.Add(10);
ax.Add(10);
cout<<"Value is "<<ax.getAccumulator();
Reset(ax);
cout<<"Value is "<<ax.getAccumulator();
return 0;
}
9
Friend Functions of Classes
A function can be a friend of more than one class at
the same time.
10
Friend Classes of a Class
• In the similar manner as friend function an entire
class can also be a friend of another class.
• In this way the members of the friend class can
have access to the members of the other class.
Read out and discuss the given handouts in groups to
know more about it and for the benefits of friend
functions
11
Reading Material
• Chapter 9
o C++ How to Program, 10th Edition, by Paul Deitel and
Harvey Deitel
• Chapter 6
o Object Oriented Programming in C++, 4th Edition, by Robert
Lafore
12