C++ program to overload extraction operator



Suppose we have a Person class with two attributes first_name and the last_name. It also has two methods called get_first_name() and get_last_name() to retrieve or set first name and last name respectively. We shall have to overload the extraction operator (<<) to print the first name and the last name to print them using cout statement.

So, if the input is like a person object with first name and last name ("Sumit", "Ray"), then the output will be First name − Sumit, Last name − Ray.

To solve this, we will follow these steps −

  • To overload extraction operator, it should be defined outside the class

  • The return type will be an ostream reference

  • The input parameters are an ostream reference variable os, and object reference variable

  • using os extract all parts of the object in proper order

  • return os object reference.

Example

Let us see the following implementation to get better understanding −

#include <iostream>
using namespace std;
class Person {
    private:
        string f_name;
        string l_name;
    public:
        Person(string first_name, string last_name) : f_name(first_name), l_name(last_name) {}
        string& get_first_name() {
          return f_name;
        }
        string& get_last_name() {
          return l_name;
        }
};
ostream& operator<<(ostream& os, Person& p) {
    os << "First name: " << p.get_first_name() << ", Last name: " << p.get_last_name();
    return os;
}
int main(){
   Person p("Sumit", "Ray");
   
   cout << p << ", he is our member.";
}

Input

p("Sumit", "Ray")

Output

First name: Sumit, Last name: Ray, he is our member.

Advertisements