Online Tutorials & Training Materials | STechies.com
Register Login

Friend Function and Class in C++

|| || 0

Friend Function and Class in C++
Stechies

Friend Class

If a class is declared as the friend of another class, then the class can access the private and protected data members of the other class. Such a class is called a friend class. To access the protected and private member, the objects of a class has to be passed in the member functions of the friend class. However, this friendship is not mutual. If class Student is a friend of class Teacher, then Teacher does not become a friend of the Student class.

Friend Function

A friend function has the ability to access the private and protected members of a class but is defined outside the scope of the class. The function prototypes are provided inside the class scope but they are not considered member functions of the class. This function can be a global function or the method of another class.

A friend can be function, member function, function template, class & class template.

We have to use a keyword friend through this keyword ‘friend’ compiler come to that this function is friend of defined class inside the class.

How to declare friend function in the class

class <class_name>
{........ arguments
	friend return type <function name> 
					(contents)
	........
}

h2 >Characteristics of friend function

The characteristics of a friend function are:

  • It can access the private and protected members of a class.
  • It is defined outside the scope of the class.
  • It can be a global function or the method of a different class.
  • It has to be declared along with the friend keyword inside the class.
  • The keyword is not used during the function definition.
  • Objects of the class cannot call a friend function as it is defined outside the scope of the class.
  • Any access specifier can be used with a friend function, and it does not affect the function.
  • Class objects are passed on as arguments with the friend function.   

Friend function in C++ example

#include <iostream>
#include <conio.h>

using namespace std;
class Caltx {
      string name;
   	int salary;
public:
   void Saly() {
      cout << "Enter the Name whose salary calculation to be done :";
      cin >> name;
      cout << "Enter Salary  of the same Person:";
      cin >> salary;
   }
   void printDetails() {
      cout << "nName : " << name << ", Salary : " << salary << endl;
   }
   friend int calculateTax(Caltx Caltx);
};
int calculateTax(Caltx Caltx) {
   int tax = (Caltx.salary / 100) * 5;
   return tax;
}
int main() {
   Caltx mobj;
   int tax = 0;
   cout << "Friend Function Example Program In C++n";

   mobj.Saly();
   mobj.printDetails();
   tax = calculateTax(mobj);
   cout << "Calculated Tax 5% : " << tax;
   getch();
   return 0;
}

 


Related Articles