To the nice answers given by Karthik T and Pubby regarding overloaded operator+()
, I would like to add one point.
Usually you would need to access private members of the MyClass
inside the overloaded operator+()
code (unlike the return "bar";
as in your presumably stripped down example). In that case, you would need to declare it as a friend
. You cannot have the operator+()
as a member of MyClass
, because the MyClass
comes on the left side of the operator +
. Refer below sample code.
#include <string>
#include <iostream>
using namespace std;
struct MyClass {
public:
MyClass() : bar("bar") {}
friend string operator+(string& str, MyClass& x);
private:
string bar;
};
string operator+(string& str, MyClass& x) {
return str + x.bar;
}
int main( int argc, char* argv[] )
{
MyClass x;
string foo("foo");
std::cout << foo + x << std::endl;
return 0;
}