Rohit Karunakaran
Rohit Karunakaran

Reputation: 27

C++ overloading the << operator

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

Upvotes: 0

Views: 92

Answers (1)

John Zwinck
John Zwinck

Reputation: 249602

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.

Upvotes: 0

Related Questions