Enter/Output Operators Overloading in C++

[ad_1]

View Dialogue

Enhance Article

Save Article

Like Article

View Dialogue

Enhance Article

Save Article

Like Article

Operator Overloading is part of Polymorphism, which allows the characteristic due to which we will immediately use operators with user-defined courses and objects.

To learn extra about this, confer with the article operator overloading in C++.

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

We are able to’t immediately use the Enter/Output Operators (>>/<<) on objects. The straightforward clarification for that is that the Enter/Output Operators (>>/<<) are predefined to function solely on built-in Information sorts. As the category and objects are user-defined knowledge sorts, so the compiler generates an error.

Instance:

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

right here, Enter/Output Operators (>>/<<)  can be utilized immediately as built-in knowledge sorts.

Instance:

class C{

};

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

c1 are variables of kind “class C”. Right here compiler will generate an error as we try to make use of Enter/Output Operators (>>/<<) on user-defined knowledge sorts.

Enter/Output Operators(>>/<<) are used to enter and output the category variable. These will be accomplished utilizing strategies however we select operator overloading as an alternative. The explanation for that is, operator overloading offers the performance to make use of the operator immediately which makes code straightforward to know, and even code dimension decreases due to it. Additionally, operator overloading doesn’t have an effect on the traditional working of the operator however gives additional performance to it.

A easy instance is given under:

C++

#embody <iostream>

utilizing namespace std;

  

class Fraction {

  

non-public:

    int numerator;

    int denominator;

  

public:

    

    Fraction(int x = 0, int y = 1)

    {

        numerator = x;

        denominator = y;

    }

  

    

    

    buddy istream& operator>>(istream& cin, Fraction& c)

    {

        cin >> c.numerator >> c.denominator;

        return cin;

    }

  

    buddy ostream& operator<<(ostream&, Fraction& c)

    {

        cout << c.numerator << "/" << c.denominator;

        return cout;

    }

};

  

int principal()

{

    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

[ad_2]

Leave a Reply