Input/Output Operators Overloading in C++

Posted in /  

Input/Output Operators Overloading in C++
vinaykhatri

Vinay Khatri
Last updated on December 23, 2024

    In C++ we use the stream extraction operators with stream statements (cin, cout) to show outputs and take input from the user. And using the C++ Operator Overloading techniques we can overload or redefine the stream extraction operators for user-defined class-based Objects.

    Like other Operator we cannot directly overload the >> stream extraction operator and << stream insertion operator because cout and cin are the objects of iostream class, and the C++ compiler would directly jump to the iostream header file class for the cout and cin definition but if we want that compiler should consider out Overloaded definition we make a global method and if we want to allow them to access private data members of the class, we must make them a friend.

    Example

    #include <iostream>
    using namespace std;
    
    class Complex
    {
     private:
        int real, imag;
     public:
        Complex(int r = 0, int i =0)
        { 
             real = r;  
             imag = i;
        }
    
    friend ostream & operator << (ostream &output, const Complex &c)
    {
        output << c.real;
        output << "+i" << c.imag;
        cout<< endl;
        return output;
    }
    
    friend istream & operator >> (istream &in,  Complex &c)
    {
        cout << "Please Enter the Real Part: ";
        in >> c.real;
        cout << "Please Enter the Imaginary part: ";
        in >> c.imag;
        return in;
    }
    };
    
    int main()
    {
       Complex c1;
       cin >> c1;
       cout << "The complex object is ";
       cout << c1;
       return 0;
    }

    Output

    Please Enter the Real Part: 12 
    Please Enter the Imaginary part: 13 
    The complex object is 12+i13

    People are also reading:

    Leave a Comment on this Post

    0 Comments