C++ friend function
Created By: chatGPT
Friend functions are a special kind of function in C++ that allow non-member functions to have access to the private and protected members of a class. This concept is useful when you need to implement certain functionalities that require access to private data, but you don't want those functions to be part of the class itself. Here's a simple example to illustrate how friend functions work.
#include <iostream>
class Box {
private:
double width;
public:
Box(double w) : width(w) {}
// Declaring a friend function
friend void printWidth(Box box);
};
// Definition of the friend function
void printWidth(Box box) {
std::cout << "Width of box: " << box.width << std::endl;
}
int main() {
Box box(10.5);
// Call the friend function
printWidth(box);
return 0;
}
In the example above:
- We define a class called Box with a private member width.
- A friend function named printWidth is declared inside the class, allowing it to access the private data.
- In the main() function, we create an instance of Box and call the friend function to print the width.
This way, the friend function is able to access the private member without being a member of the class.