Eliezer
Eliezer

Reputation: 7357

Template Parameter Inheritance in C++

I haven't written C++ in a while, so I'm a bit rusty. If I have a class like this:

class JsonType{
    protected:
        map<string, JsonType>* objects;
}

and a class that inherits from that:

class JsonObject : public JsonType{
    public:
        JsonObject(){
            this->objects = new map<string, JsonObject>();
        }
}

why would I be getting a compiler error cannot convert...JsonObject...to...JsonType? Shouldn't that be legal, since JsonObject is a JsonType?

Upvotes: 1

Views: 605

Answers (2)

StilesCrisis
StilesCrisis

Reputation: 16320

objects doesn't use JsonObject for its value_type, it uses JsonTypes.

In other words you are allocating the wrong kind of map to store into objects.

Upvotes: 1

DomenicDatti
DomenicDatti

Reputation: 672

You can add JsonObject objects to the map, but the types do not match for initialization.

Edit: You have to initialize it as:

this->objects = new map<string, JsonType>();

But if you have either objects:

JsonType js = new JsonType();

or

JsonObject js2 = new JsonObject();

or

JsonType js3 = new JsonObject();

You can add any of these objects to the map initialized as above.

Upvotes: 1

Related Questions