0

I made a lib to parse JSON content with XCode and the main class JSONObject has the operator= overloaded, as you can see:

    class JSONObject
    {   
        //...

    public:

        JSONObject();
        ~JSONObject();

        //...

        void operator=(int);
        void operator=(long);
        void operator=(float);
        void operator=(double);
        void operator=(bool);
        void operator=(std::string);

        //...
    };

The issue here is that at the moment of use operator=(string) the operator=(bool)is invoked:

    JSONObject nItem;
    nItem = "My New Item"; // <--- Here is what the problem is founded.
    innerObj["GlossSeeAlso"]+= nItem;

enter image description here

The workaround that i found to "fix" this problem was specify the string type:

nItem = (string)"My New Item"; //"Fix 1"

nItem = string("My New Item"); //"Fix 2"

The lib and sample was compiled with:

Apple LLVM version 8.0.0 (clang-800.0.38)  

The complete code can be founded here.

I will appreciate any help to understand this issue, why the operator=(bool) is invoked instead of operator=(string).

Jorge Omar Medra
  • 978
  • 1
  • 9
  • 19

1 Answers1

1

Type of the string literal "My New Item" is char const[12]. Such a type needs to be converted to one of the types that the overloaded operator= functions support.

Due to various conversion rules, the compiler decided, correctly, that char const[12]char const*bool is a better conversion than char const[12]std::string. Hence, operator=(bool) is called. The reason why char const[12]char const*bool is a better conversion than char const[12]std::string is that the former is a sequence of standard conversions while the latter involves a user defined conversion.

To allow a string literal to be used in assignment, add another overload.

JSONObject& operator=(char const*);

PS You should change the return value of all the operator= functions to JSONObject& to make them idiomatic. See What are the basic rules and idioms for operator overloading? for more information.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • That's correct, i made the correction and it fix the issue. The explication that you offered me makes me sense, choosing `const char*` vs `string`. Thanks. – Jorge Omar Medra Apr 06 '18 at 19:00
  • Please, can you explain more about make the operator idiomatic? I designed them (operatos=(long|double|string|bool) to set a value. – Jorge Omar Medra Apr 06 '18 at 19:04
  • @JorgeOmarMedra, you are welcome. I added a link to another SO post in my answer. – R Sahu Apr 06 '18 at 19:06