I created the following code for educational purposes and encountered a scenario for which I expected an error to occur, but no error occurred. Here is the class,
#include <string.h> // strcpy_s and strcat_s, not available in "<string>" #include <string> #include <iostream> class String { char *p; int len; public: String() { len = 0; p = '\0'; }; ~String() { delete p; }; String(const char * s); String(const String & s); friend String operator+(const String& a, const String &); friend std::ostream& operator<<(std::ostream& os, String const& m); }; String::String(const char * s) { len = strlen(s); p = new char[len + 1]; strcpy_s(p, len + 1, s); } String operator+(const String & l, const String & r) { String temp; temp.len = l.len + r.len; int temp_buffer_size = temp.len + 1; temp.p = new char[temp_buffer_size]; strcpy_s(temp.p, temp_buffer_size, l.p); strcat_s(temp.p, temp_buffer_size, r.p); return temp; } std::ostream & operator<<(std::ostream & os, String const & m) { return os << m.p; } int main() { String right("right"); String out = "left " + right + " "; std::cout << out; return 0; } If I run this code, it works fine. However my confusion comes from String out = "left " + right + " ";. Why does this line work, why did it not create an error such as "Cannot add const char * with String"? I am guessing here that it implicitly creates a String object while passing "left" as the constructor, but I was hoping for more evidence for this.
mainfunction is sufficient for the program to run. The other functions are unnecessary."left " + rightthe functionString operator+(const String & l, const String & r)is a match if"left"can be turned intoString, which it can be via the constructorString(const char * s);Try making the single argument constructors of theStringclassexplicitto get the error you expected.String out = "left " + right + " ", the compiler first tries to evaluate"left " + right, which can be done by performing a single conversion on"left"i.e. doingoperator+(String("left"), right). Thatoperator+()returns aString, so we're left withoperator+(...) + "right". The same logic then applies with doing a conversion on"right".