user2015453
user2015453

Reputation: 5104

derived classes in maps

i have two independent class hierarchies, starting at BaseClass1, BaseClass2

this is what I want to do:

struct BaseClass1 {
  virtual void obtain_map(std::map<int,BaseClass2> &map) = 0;
}

Subclasses of BaseClass1 override the obtain_map. But the problem is that those sublcasses should be able to use subclasses of BaseClass2 in the map parameter. (So in this sense, subclasses of the two "independent" hierarchies are actually related, or rather can be if the subclass designers want)

How can I accomplish this, or am I forced to create my own map class from scratch?

Upvotes: 0

Views: 158

Answers (2)

billz
billz

Reputation: 45410

STL containers only store fixed size objects. If yo push BaseClass2 derived class object to std::map<int,BaseClass2>, objects will be sliced to BaseClass2 type.

If you want std::map to store subclasses of BaseClass2, you need to store pointer(smart pointer) in map.

For example:

  struct BaseClass1 {
    virtual void obtain_map(std::map<int, std::unique_ptr<BaseClass2>> &map) = 0;
  }

   struct DerivedClass1 : public BaseClass1 {
   virtual void obtain_map(std::map<int, std::unique_ptr<BaseClass2>> &map)
   {
      // implementation
   }
 }

Storing smpart pointers has the advances compare to raw poiter because you don't need to manually delete memories the pointers are pointing to.

Upvotes: 0

Foggzie
Foggzie

Reputation: 9821

If you derive your classes like so and use pointer as the second map template parameter (a smart pointer like std::unique_ptr will save you some memory management trouble):

struct BaseClass1 {
    virtual void obtain_map(std::map<int, std::unique_ptr<BaseClass2>> &map) = 0;
};
struct DerivedClass1 : public BaseClass1 {
    virtual void obtain_map(std::map<int, std::unique_ptr<BaseClass2>> &map) override
    {
    }
};

You can still pass in maps with derived versions of BaseClass2 as the second type:

struct DerivedClass2 : public BaseClass2;
// ...

std::map<int, std::unique<DerivedClass2>> mdc2;
DerivedClass1 dc1;
dc1.obtain_map(mdc2);

Upvotes: 1

Related Questions