Friend Function
In : BCA Subject : OOPS and Data StructuresA friend function is a special kind of function that can access the private and protected members of a class — even though it is not a member of that class.
Example :
#include <iostream>
using namespace std;
// Step 1: Define the class
class Box {
private:
double length, width, height;
public:
// Constructor
Box(double l, double w, double h) {
length = l;
width = w;
height = h;
}
// Step 2: Declare the friend function inside the class
friend double calculateVolume(Box box);
};
// Step 3: Define the friend function outside the class
double calculateVolume(Box box) {
return box.length * box.width * box.height;
}
// Step 4: Use in main
int main() {
Box myBox(3.0, 4.0, 5.0);
// Call the friend function
cout << "Volume is: " << calculateVolume(myBox) << endl;
return 0;
}