Friend Functions (Detailed)
Friend Functions (Detailed)
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.
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
6
Friend Functions of Classes
• A friend function may or may not be a member of
another 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
10
Friend Classes of a Class
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