I have a String class and I want to
overload + to add two String*
pointers.
Why?
something like this doesn't work:
String* operator+(String* s1, String*
s2);
This is c++ core functionality. You cannot change it like that.
Is there any way to avoid passing by
reference.
You can pass by reference, by pointer or by value.
By value is inefficient (as temporaries get created and copied for no valid reason*)
By pointers is not usable in this case (adding pointers is core language functionality). In fact, references were added to the language to combine the efficiency of passing pointers as arguments (to overloaded operators) with the convenient syntax of passing values. In other words, references are a language feature created with your specific situation in mind. They are the optimal solution.
By reference is the usually accepted solution. Could you please tell us why this is not good in your situation?
Consider this example:
String* s1 = new String("Hello");
String* s2 = new String("World");
String* s3 = s1 + s2;
This looks like Java or C# code, translated to C++ syntax. Don't do that. This mentality is called "I can program C in any language" and it usually compounds the inherent problems of whatever mentality you're trying to port to C++ with the inherent problems of C++, without the advantages of either.
I'm not saying you're doing that, I'm just saying to make sure you're not already doing it :).
I need this kind of addition to work.
Please suggest.
You can define an additional smart pointer class for holding your strings. It doesn't need to do much (just a struct ptr { String* _value; /* add your syntax sugar and operators here */ }
would suffice. That said, it is still a bad idea to do this just for the sake of adding pointers.