How to overload [ ] operator when using pointers to polymorphic objects?
asked 15 hours ago by @qa-lv6nvtt7ngmg00qem02d 0 rep · 183 views
c++ pointers polymorphism operator overloading
I'm making a JSON parser. My goal is to try and implement it so I can chain accessing keys like so:
std::string errorMsgOutput;
std::optional<double> myNumber = myJSONObj["topKey"]["subkey"].getNumber(errorMsgOutput);
The base of my class hierarchy is called JSONBase. The problem is, just using JSONBase to store data and return types means I won't be able to use polymorphic overridden methods which require using JSONBase*. However I have no idea how I'd write an overloaded [] operator to both return JSONBase* and also work with chaining (or better yet, using smart pointers).
How would I make this work?
My current setup looks something like this:
class JSONBase {
protected:
std::optional<std::string> mErr = std::nullopt;
public:
std::optional<double> getNumber(std::string& errMsg) {
errMsg = "Error attempting to retrieve number from non-number JSON object";
return std::nullopt;
}
JSONBase& operator [] (const std::string& key) {
this->mErr = "Error attempting to retrieve indexed value from non-array JSON object";
return this;
}
}
//Stores JSON <key, value> objects
class Object: public JSONBase {
private:
std::unordered_map<std::string, JSONBase> mData;
public:
JSONBase& operator [] (const std::string& key) {
if (this->mErr) {
return this;
}
if (!this->mData.contains(key)) {
this->mErr = "JSON dictionary does not contain key \"" + key + '\"';
return this;
}
return this->mData[key];
}
}
//Stores JSON number data
class Number: public JSONBase {
private:
double mData;
public:
std:optional<double> getNumber(std::string& errMsg) {
if (this->mErr) {
errMsg = *this->mErr;
return std::nullopt;
}
return this->mData;
}
}
This is simplified and leaves out the Array, Boolean, and String classes, but I plan to implement those in the exact same way.