📌 Display Values using Friend Function in C++


🔹 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

  1. Create a class Number with a private variable.
  2. 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

  1. Private Data Access:

    • The value variable is private and cannot be accessed outside the class.
    • The friend function display() is allowed to access it.
  2. Function Call:

    • In main(), we create an object num(100).
    • We call display(num), which prints the value.

🚀 Need More Examples? Let Me Know! 🚀

Post a Comment

0 Comments