Friend functions, and bridge between classes
Friend Function
In classes and object-oriented programming (OOP), non-member functions cannot access private or protected members of a class.
A friend function in C++ is not a member of a class but is granted access to that class's private and protected members. It allows the function to access and modify the internal data of the class, providing a way to operate on class objects in a controlled manner.
#include <iostream>
class Box {
private:
int length;
int width;
int height;
public:
Box() : length(1), width(2), height(3) {}
// Friend function declaration
friend void printBoxDimensions(Box);
};
// Friend function definition
void printBoxDimensions(Box b) {
cout << "Length: " << b.length << std::endl;
cout << "Width: " << b.width << std::endl;
cout << "Height: " << b.height << std::endl;
}
int main() {
Box myBox;
printBoxDimensions(myBox); // Access private members via friend function
return 0;
}
Friends as Bridges:
to handle private data from multiple classes, each class must grant friendship to the function or method that needs to access their private members.
A friend function can only access the private data of the class in which it’s declared as a friend. To access private data of another class, it needs to be a friend of that class as well.
Post a Comment