Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Fail without Operator Definition

I'm currently porting a C++ application to a slightly restricted environment. The application uses the STL, string and stream classes. I'm rewriting simplified versions of these that will play nicely in my environment.

What I'm concerned about is that my application is compiling even without all the necessary operator definitions. For example, for my string classes I defined:

string operator+ (const string& lhs, const string& rhs);

and this was enough. However, I noticed there were often cases that had mystring + "some constant string" and this isn't defined in my code anywhere. When I explicitly added it it was used:

string operator+ (const string& lhs, const char* rhs);

What was going on before that? It compiled successfully before I added the second function. Surely the compiler wouldn't be able to infer how to concatenate c-style strings to my string class.

I'm getting strange behaviour in my program now and I'm wondering if it's due to other operators left undefined. Is there any way to enforce the compiler to require such operator definitions if it's needed by the program?

P.S. My string class is in a unique namespace and unrelated to std::

like image 735
hayesti Avatar asked Oct 20 '11 19:10

hayesti


2 Answers

It's impossible to be certain without seeing the rest of your code, but in this case it's probably not too hard to guess either. You almost certainly have a constructor for your string that takes a char const * as its parameter, so what's happening is that the compiler is using that ctor to convert the char const * to a string, then using string operator+ (const string& lhs, const string& rhs); to concatenate that.

Allowing this to happen is one of (if not the) primary reason for overloading these operators with globals instead of member functions. As member functions they can convert the right operand, but not the left.

like image 189
Jerry Coffin Avatar answered Oct 06 '22 00:10

Jerry Coffin


When you passed a const char*, a string object was probably constructed and passed to operator+. If you step through the code in a debugger you will probably be able to verify the constructor is being called.

like image 32
Dabbler Avatar answered Oct 06 '22 00:10

Dabbler