0

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.

  1. Why does the ostream object in operator<< function need to be passed by reference?
  2. Why cant the return type of the function be 'std::ostream' instead of 'std::ostream&' ?

  3. 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<<" ";

1 Answer 1

0

Not all operator overloading requires passing by reference. For example if you write a class which encapsulates a 2D point and you make an operator- for two of these, you'd probably take the arguments by value (since they are small and simple types with "value semantics"), and it would return the distance by value (because there's presumably no preallocated distance object which could be returned, you are creating a new one). That is:

dist2d operator-(point2d a, point2d b) { return {a.x - b.x, a.y - b.y}; } 

std::ostream is not copyable, because what would it mean to copy a stream (which does not contain its own history)? So you have to pass it by reference or pointer always.

Sign up to request clarification or add additional context in comments.

3 Comments

There's also the issue of inheritance, you want to be able to call operator<< on any type derived from ostream.
So, if i use the << operator on any object inherited from the ostream class, it will get overloaded by this new definition above .(sorry i am new to this stuff so i get confused with all the terminology.)
@RohitKarunakaran I would put it like this, if you use << on an ostream derived class and your Passenger class then (in the absense of any better match) your operator<< will get called. There's nothing to stop you defining an operator<< for ofstream (for instance), it's just not a very useful thing to do.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.