C++ operator overloading error

hi,
I defined my own String class and overloaded the output operator with

friend ostream& operator<<(ostream& os, const myString& str);
//overloads the << operator so it can be used to output values of type myString

which works fine. Until I try to execute the following statement:

// + concatenation operator is already defined for myString
cout << (str4=str2+str) << endl; //This statement concatenates str to str2, then assigns it to str4 and returns str4, right?

And, I get error

error: no match for �operator<<' (operand types are �std::ostream' {aka �std::basic_ostream<char>'} and �void')
  cout << (str4=str2+str) << endl;
  ~~~~~^~~~~~~~~~~~~~~~~~

The above code works fine when I change the concatenation statement as follows:

str4=str2+str;
cout << str4 << endl;

What did I miss?

What type does your 'operator =' return?

void operator=(const myString& rside);

That means the expression 'str2=whatever' returns void -- or rather, returns nothing. So there's nothing to cout.

Instead have it return const myString & and at the end, put return(*this);

I changed the member function like this:

myString operator=(const myString& rside)

and return rside at the end.

Returning rside is clever and ought to work, but return-by-value is a bad idea -- that makes a local copy, which isn't just wasteful, in some circumstances that's an infinite recursion and out-of-memory crash. Assignment operators shouldn't use copy constructors.

You pretty much have to return a reference here.

const myString &operator=(const myString& rside)
1 Like

makes sense. Thanks for the help.

1 Like