Skip to main content

Simple Program for Friend Function

1 min read Updated June 30, 2026
Share:
On this page (7sections)

Friend Function Definition:

If a function is friend function of a class, that friend function is not the actual member of the class.But which function has rights to access to all private and protected members (variables and functions).

For Better Understanding,

Simple Program for Friend Function Algorithm/Steps:

  • STEP 1: Start the program.
  • STEP 2: Declare the class name as Base with data members and member functions.
  • STEP 3: The function get() is used to read the 2 inputs from the user.
  • STEP 4: Declare the friend function mean(base ob) inside the class.
  • STEP 5: Outside the class to define the friend function and do the following.
  • STEP 6: Return the mean value (ob.val1+ob.val2)/2 as a float.
  • STEP 7: Stop the program.

Simple Program for Friend Function

#include<iostream.h>
#include<conio.h>

class base {
    int val1, val2;
public:

    void get() {
        cout << "Enter two values:";
        cin >> val1>>val2;
    }
    friend float mean(base ob);
};

float mean(base ob) {
    return float(ob.val1 + ob.val2) / 2;
}

void main() {
    clrscr();
    base obj;
    obj.get();
    cout << "\n Mean value is : " << mean(obj);
    getch();
}

Sample Output

Enter two values: 10, 20
Mean Value is: 15

Learn the concept first, then study the code:

Frequently Asked Questions

What does this C++ program do?
It is a C++ example program that demonstrates Simple Program for Friend Function, including the complete source code and the expected sample output.
How do I compile and run this C++ program?
Save the code in a `.cpp` file, compile it with `g++ filename.cpp -o program`, then run it with `./program` (or `program.exe` on Windows).
What concepts does this example use?
This example uses reading user input and user-defined functions, illustrating a common pattern in C++ programming.

Related Tutorials

Search tutorials