1

I've noticed that when people overload the + operator they often use two arguments when I've been able to simply pass in 1 and get the same result. What is the reasoning behind why the version with 2 arguments is preferred, when doing it the way with 1 seems to yield the same result?

Below are two segments from my code. (I am using the cctype library for the c string manipulation.)

One-argument version:

myString operator + (const myString& rhs){
  int length = strlen(str) + strlen(rhs.str);
  char* buff = new char[length +1];

  strcpy(buff,str);
  strcat(buff,rhs.str);
  buff[length] = '\0';

  myString temp(buff);
  delete[]buff;
  return temp;
}

Two-argument version:

friend myString operator + (const myString& lhs,const myString& rhs){
  int length = strlen(lhs.str) + strlen(rhs.str);
  char* buff = new char[length + 1];
  
  strcpy(buff,lhs.str);
  strcat(buff,rhs.str);
  buff[length] = '\0';
  
  myString temp(buff);
  delete[] buff;
  
  return temp;
}
MmMm SsSs
  • 95
  • 7
  • 3
    see: https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading/4421729#4421729 – NathanOliver May 14 '22 at 19:56
  • What about the `this` parameter? – Ulrich Eckhardt May 14 '22 at 19:57
  • @273K I don't follow. The target that was used looks exactly like a duplicate to me. Both questions are asking pretty much the same thing. They're certainly not unrelated. One way of seeing that is the answer you posted here would fit on the target question. – cigien May 14 '22 at 22:38
  • @273K Yes, sorry, that's the one I meant. Aren't both the questions asking "why can operator+ sometimes take 2 arguments, and sometimes 1?" They really look like duplicates to me. – cigien May 14 '22 at 22:55
  • @cigien That post does not answer this question above: *why the version with 2 arguments is preferred, when doing it the way with 1 seems to yield the same result*. And I tried to answer with the example, why a free operator can be preferable. Nathan's link did the same, but I was not very carefully in my search attempt. – 273K May 14 '22 at 23:02

0 Answers0