Friend Function Example in C++


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

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;
    return temp;
int main()
    Complex c1,c2,c3;
    cout<<"\nReal : "<<c3.real;
    cout<<"\nImg : "<<c3.img;
    return 0;
To download raw file Click Here


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


Inheritance Examples

Hierarchical Inheritance

Hybrid Inheritance

Multilevel Inheritance

Multiple Inheritance

Single Level Inheritance

Class and Objects

Constructor Example

Destructor Example

Operator Overloading Example

Operator and Function Example

List of Programs

Pointer Examples

Memory Management Examples

Pointers and Arrays

Virtual Function Examples

Learn All in Tamil © Designed & Developed By Tutor Joes