0

I want to build data structure, incapsulating map , but not template!

struct mananager
{
    map<KeyClass, ValueClass> myMap;
}

class KeyClass
{
  //
}
class ValueClass
{
  //
}

class derivedKeyClass : public KeyClass
{
  //
}

class derivedValueClass : public ValueClass
{
 //
}
 manager m;
 derivedKeyClass dkey;
 derivedValueClass  dValue;
 m.myMap[dkey] = dValue;

Is it correct? Or should use pointer and can`t change a type for key map<KeyClass, ValueClass*> myMap;

YAKOVM
  • 9,805
  • 31
  • 116
  • 217
  • Both `dkey` and `dValue` are _sliced_ in `m.myMap[dkey] = dValue;`. Changing the value type of the map to a pointer won't entirely fix that. – 1201ProgramAlarm Mar 23 '21 at 23:29
  • @1201ProgramAlarm - what is sliced? if I use always same kye type. and a pointer for a value - could it work? – YAKOVM Mar 23 '21 at 23:34
  • @Yakov - question: if always using same key type, why create ``derivedKeyClass``? – trozzel Mar 23 '21 at 23:56
  • @trozzel - now it is always int. but i want to make this class maximum possible generic. Thus i wanted a key also to be generic. if not possible int key is also ok – YAKOVM Mar 24 '21 at 00:21
  • @Yakov That is what templates are for! – Remy Lebeau Mar 24 '21 at 02:12
  • 1
    @Yakov "*what is sliced?*" - if something is declared as `KeyClass` and you assign it a `derivedKeyClass`, [slicing occurs](https://stackoverflow.com/questions/274626/what-is-object-slicing). Same with `ValueClass` and `derivedValueClass`. Polymorphism only works with pointers and references, and you can't use either of those for a map's `key_type` (well, not easily, anyway), but you can use a `ValueClass*` pointer for its `mapped_type`, eg: `map m; KeyClass key; derivedValueClass dValue; m[key] = &dValue;` – Remy Lebeau Mar 24 '21 at 02:13

0 Answers0