I am trying to overload the << operator in c++, I have implemented the code properly but I have a few doubts about the overall working of the overloading concept.
- Why does the ostream object in operator<< function need to be passed by reference?
Why cant the return type of the function be 'std::ostream' instead of 'std::ostream&' ?
Is it the property of the ostream class that requires the 'operator<<' function to return a memory address or do all the operator overloading need to be passed by reference and the return type should also be a reference?
Here is the code.
#include<iostream> enum MealType{NO_PREF,REGULAR,LOW_FAT,VEGETARIAN}; struct Passenger{ char name[30]; MealType mealPref; bool freqFlyer; int passengerNo; }; //Overloading the << operator std::ostream& operator<<(std::ostream& out,const Passenger& pass){ out<<pass.name<<" "<<pass.mealPref; if(pass.freqFlyer){ out<<" "<<"Passenger is a freqent flyer "; } else{ out<<" "<<"Passenger is not a frequent flyer "; } return out; } int main(){ Passenger p1 = {"Jacob",LOW_FAT,false,2342}; std::cout<<p1; return 0; } EDIT 1: Why do i have to use the << operator in the overloading function definition. Does it function like a bitwise shift or like << in std::cout<<" ";