🔹 What is a Friend Function?
- A friend function is a function that is not a member of a class but has access to private and protected members of the class.
- It is declared inside the class using the
friend
keyword.
📌 Example: Display Values using Friend Function
🚀 Approach
- Create a class
Number
with a private variable. - Use a friend function to display the private value.
🔹 C++ Code
#include <iostream>
using namespace std;
class Number {
private:
int value;
public:
// Constructor
Number(int v) {
value = v;
}
// Friend function declaration
friend void display(const Number &n);
};
// Friend function definition
void display(const Number &n) {
cout << "The value is: " << n.value << endl;
}
int main() {
Number num(100); // Create object
display(num); // Call friend function
return 0;
}
🔹 Output
The value is: 100
📌 Explanation
-
Private Data Access:
- The
value
variable is private and cannot be accessed outside the class. - The friend function
display()
is allowed to access it.
- The
-
Function Call:
- In
main()
, we create an objectnum(100)
. - We call
display(num)
, which prints the value.
- In
0 Comments