OOP in C++ (Friend Function)
OOP in C++ (Friend Function)
3
Friend Function
Concept:
•A class’s friend function is defined outside that class’s scope,
but it has the right to access all private and protected
members of the class.
•For accessing the data, the declaration of a friend function
should be done inside the body of a class.
•Even though the prototypes for friend functions appear in
the class definition, friends are not member functions.
4
Friend Function
Concept:
•A friend function in C++ is a function that is preceded by the
keyword “friend.”
•By using the keyword friend compiler knows the given
function is a friend function.
5
Friend Function
Syntax:
class className {
... .. ...
friend returnType functionName(arguments);
... .. ...
}
• The function can be defined anywhere in the program like a
normal C++ function. The function definition does not use
either the keyword friend or scope resolution operator.
6
Friend Function
Example: Working of friend Function
class Distance { // friend function definition
private: int addFive(Distance d) {
int meter;
//accessing private members from the friend function
// friend function d.meter += 5;
friend int addFive(Distance); return d.meter;
}
public:
Distance() : meter(0) {} int main() {
Distance D;
}; cout << "Distance: " << addFive(D);
return 0;
Output }
Distance: 5
7
Friend Function
Characteristics of friend function:
•A friend function can be declared in the private or public
section of the class.
•It can be called a normal function without using the object.
•A friend function is not in the scope of the class, of which it
is a friend.
•A friend function is not invoked using the class object as it is
not in the class’s scope. 8
Friend Function
Characteristics of friend function:
•A friend function cannot access the private and protected
data members of the class directly. It needs to make use of a
class object and then access the members using the dot
operator.
•A friend function can be a global function or a member of
another class.
9
Friend Function
Example: Add Members of Two Different Classes
// forward declaration
class ClassB;
class ClassA {
public:
// constructor to initialize numA to 12
ClassA() : numA(12) {}
private:
int numA;
An Example: public:
// constructor to initialize numB to 1
ClassB() : numB(1) {}
class ClassB; // forward declaration // member function to add numA from ClassA and numB from ClassB
int add() {
class ClassA { ClassA objectA;
private: return objectA.numA + numB;
int numA; }
};
friend class ClassB; // friend class declaration
int main() {
public: ClassB objectB;
// constructor to initialize numA to 12 cout << "Sum: " << objectB.add();
ClassA() : numA(12) {} return 0;
}; }
Output
Sum: 13 15