Insertion Overload 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 to allow us to print complex numbers.

The operator<< function takes an output stream o and a complex number c1 as input, and returns the output stream o after printing the complex number in the format real+imaginaryi.

In the main function, a complex number c1 is initialized with real and imaginary values. Then, the operator<< is used to print c1 using the cout object. The same thing is achieved using the operator<< function explicitly by calling operator<<(cout,c1).

Source Code

#include<iostream>
using namespace std;
class Complex
{
public :
    int real;
    int img;
    friend ostream & operator << (ostream &o,Complex &c1);
};
ostream & operator << (ostream &o,Complex &c1)
{
    o<<c1.real<<"+i"<<c1.img;
    return o;
}
int main()
{
    Complex c1;
    c1.real=5;
    c1.img=3;
    cout<<c1;
    operator<<(cout,c1);
    return 0;
}
To download raw file Click Here

Output

5+i35+i3

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