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++
#include <iostream>
using namespace std;
class Fraction {
private:
int numerator;
int denominator;
public:
Fraction(int x = 0, int y = 1)
{
numerator = x;
denominator = y;
}
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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!
Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!
Last Updated :
27 Oct, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...