Overloading stream insertion(<>) operators in C++
In this tutorial, we are going to see how we can overload stream insertion(<<) and extraction operators(>>) in C++. Overloading is an important aspect of any object-oriented programming language. Operator overloading refers to the overloading of the operators. If you don’t have much knowledge on the subject, spend some of your time here: Operator Overloading in C++
In this C++ tutorial, we will be overloading the insertion and the extraction operator. In general, the insertion operator(<<) is used for output, and the extraction operator(>>) is used for taking input. Let’s see how these can be overloaded.
An important thing to remember here is that the overloading function must be a friend of the class because we won’t be creating an object in order to call it.
You can see an example program in C++ that demonstrates very well how these insertion and extraction operators can be overloaded. Have a look at the code at each step.
#include <iostream> #include <string> using namespace std; class Name { private: string fname, lname; public: Name(string f= " ", string l = "") { fname = f; lname = l; } friend ostream & operator << (ostream &o, const Name &n); friend istream & operator >> (istream &i, Name &n); }; ostream & operator << (ostream &o, const Name &n) { o << "First Name is: " << n.fname << endl; o << "Last Name is: " << n.lname << endl; return o; } istream & operator >> (istream &i, Name &n) { i >> n.fname; i >> n.lname; return i; } int main() { Name name; cout << "Enter name:" << endl; cin >> name; cout << name; return 0; }
The above program gives the output:
Enter name: Ranjeet Verma First Name is: Ranjeet Last Name is: Verma
Thank you.
Also read: Function Overloading in C++
Leave a Reply