Search code examples
c++vectoroperator-overloadingpush-back

Is using the overloading << operator as push_back a good idea?


I've been practicing with operator overloading in order to comprehend it better and I came across using the << operator with vectors like this:

void operator<<(std::vector<int> &vector, int value){
    vetor.push_back(value);
}

Now I know that this isn't really a good idea and that I should avoid doing this but I'd like to listen to someone more experienced in the subject in order to help me understand the << operator and the ostream class in a better way.


Solution

  • Now I know that this isn't really a good idea and that I should avoid doing this

    Your knowledge is correct. There are two issues with this:

    • It's a bad idea to define operators that don't involve your own types. Technically, the standard doesn't guarantee that it won't add a global operator<<(std::vector<int> &, int) in future, which would break the forward compatibility of a program that defines such overload.

      Furthermore, library programmers with the same bad idea may potentially make the same decision, breaking the compatibility with your program. This makes such idea extra bad for library code.

    • Unlike functions, operators don't have names that describe them so as a rule of thumb in order to keep programs understandable, operator overloads should ideally implement operations that are analogous to their built-in counterparts.

      There is precedent for violation of this rule of thumb in the standard library, such as character output stream insertion operator, and the range adaptor pipe operator. Such approach increases the number of different things one operator means, and it should not be taken lightly.