logo of SA Coder
        Menu
sign in

      References



Friend Functions



Friend functions in C++ provide a way to grant a non-member function access to the private members of a class. This allows the function to manipulate the data members of the class without violating encapsulation. A friend function is declared using the keyword 'friend' and can access all private and protected members of the class for which it is a friend.



Here is an example program to illustrate the usage of friend functions in C++


copy

#include <iostream>
using namespace std;

class Rectangle {
  int width, height;
public:
  Rectangle() {}
  Rectangle(int w, int h) : width(w), height(h) {}
  friend int area(Rectangle rect);
};

int area(Rectangle rect) {
  return rect.width * rect.height;
}

int main () {
  Rectangle rect(3, 4);
  cout << "Area of rectangle is: " << area(rect) << endl;
  return 0;
}



In the above program, we define a class Rectangle with private members width and height. We then declare a non-member function 'area' as a friend of the Rectangle class. This allows the 'area' function to access the private members of the Rectangle class.



The 'area' function takes a Rectangle object as its argument and calculates the area of the rectangle using the formula width * height. In the main function, we create a Rectangle object with width 3 and height 4 and call the 'area' function to calculate its area.



Output


copy

Area of rectangle is: 12


Summary



friend functions in C++ provide a way to grant a non-member function access to private members of a class without breaking encapsulation. By declaring a function as a friend, it gains access to all private and protected members of the class. This feature is useful when designing complex programs that require close interaction between classes and functions.



Please login first to comment.