Open In App

Input/Output Operators Overloading in C++

Improve
Improve
Like Article
Like
Save
Share
Report

Operator Overloading is a part of Polymorphism, which enables the feature because of which we can directly use operators with user-defined classes and objects.

To read more about this, refer to the article operator overloading in C++.

Input/Output Operators(>>/<<) Overloading in C++

We can’t directly use the Input/Output Operators (>>/<<) on objects. The simple explanation for this is that the Input/Output Operators (>>/<<) are predefined to operate only on built-in Data types. As the class and objects are user-defined data types, so the compiler generates an error.

Example:

int a;
cin>>a;
cout<<a<<endl;

here, Input/Output Operators (>>/<<)  can be used directly as built-in data types.

Example:

class C{

};

int main() 
{
    C c1;
    cin>>c1;
    cout<<c1;
    return 0;
}

c1 are variables of type “class C”. Here compiler will generate an error as we are trying to use Input/Output Operators (>>/<<) on user-defined data types.

Input/Output Operators(>>/<<) are used to input and output the class variable. These can be done using methods but we choose operator overloading instead. The reason for this is, operator overloading gives the functionality to use the operator directly which makes code easy to understand, and even code size decreases because of it. Also, operator overloading does not affect the normal working of the operator but provides extra functionality to it.

A simple example is given below:

C++




// C++ Program to implement
// Input/Output Operators
// Overloading
#include <iostream>
using namespace std;
  
class Fraction {
  
private:
    int numerator;
    int denominator;
  
public:
    // constructor
    Fraction(int x = 0, int y = 1)
    {
        numerator = x;
        denominator = y;
    }
  
    // Operator Overloading Performed
    // Friend function used because of two classes
    friend istream& operator>>(istream& cin, Fraction& c)
    {
        cin >> c.numerator >> c.denominator;
        return cin;
    }
  
    friend ostream& operator<<(ostream&, Fraction& c)
    {
        cout << c.numerator << "/" << c.denominator;
        return cout;
    }
};
  
int main()
{
    Fraction x;
    cout << "Enter a numerator and denominator of "
            "Fraction: ";
    cin >> x;
    cout << "Fraction is: ";
    cout << x;
    return 0;
}


Output:

Enter a numerator and denominator of Fraction: 16 7
Fraction is: 16/7


Last Updated : 27 Oct, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads