There are many similar questions and I found both pro and against reasons to use this pattern so I am asking this here:
I need to make a JSON implementation in C++ (
is there any specific reason why not to do this?
Yes. What you obtain with this, is UB. The problem arises from the std::
containers not supporting polymorphism. They were not designed to be inherited from (no virtual destructor) and this means you cannot write a correct/safe destructor sequence.
Instead, your solution probably should look like this:
namespace XYZ { // <-- cannot have same name as class here
class JSON { };
class object : public JSON {
std::unordered_map values;
public:
JSON& operator[]( const std::string& key );
};
class vector : public JSON {
// same here
};
...
};