Friend Function Example in C++


Description:

C++ Friend Functions. A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions.

Example Program:

Here is the simple program using friend function in C++.

Source Code

#include<iostream>
using namespace std;
class Complex
{
public :
    int real;
    int img;
    friend Complex operator +(Complex c1,Complex c2);
};
Complex operator+(Complex c1,Complex c2)
{
    Complex temp;
    temp.real=c1.real+c2.real;
    temp.img=c1.img+c2.img;
    return temp;
}
int main()
{
    Complex c1,c2,c3;
    c1.real=5;
    c1.img=3;
    c2.real=10;
    c2.img=5;
    c3=c1+c2;
    cout<<"\nReal : "<<c3.real;
    cout<<"\nImg : "<<c3.img;
    return 0;
}
To download raw file Click Here

Output

Real : 15
Img : 8

Basic Programs


Flow Control

IF Statement Examples


Switch Case

Goto Statement

Break and Continue

While Loop

Do While Loop

For Loop

Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples



Learn All in Tamil © Designed & Developed By Tutor Joes