Friend Function Example in C++


This code defines a class Complex which represents a complex number with a real and an imaginary part. The class has a constructor, which initializes the real and imaginary parts of the complex number, and a friend function operator+ which overloads the + operator for two complex numbers. The operator+ function takes two complex numbers c1 and c2 as input, and returns a new complex number which is the sum of the two complex numbers.

In the main function, two complex numbers c1 and c2 are initialized with real and imaginary values. Then, the + operator is used to add c1 and c2 and store the result in c3. Finally, the real and imaginary parts of c3 are printed.

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

Program List


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


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