I'm wondering if it's possible to create a map of pointers of inherited classes. Here's an example of what I'm trying to do:
#include <string>
#include <map>
using namespace std;
class BaseClass
{
string s;
};
class Derived1 : public BaseClass
{
int i;
};
class Derived2 : public Derived1
{
float f;
};
// Here's what I was trying, but isn't working
template<class myClass>
map<string, myClass>m;
int main()
{
// Add BaseClasses, Derived1's, and/or Derived2's to m here
return 0;
}
The errors I get are:
main.cpp(23): error C2133: 'm' : unknown size main.cpp(23): error C2998: 'std::map<std::string,myClass>m' : cannot be a template definition
I get why I'm getting this error, but I'm wondering if it's possible to create a map that can hold different levels of inherited classes? If not, is it possible to create some sort of management system that can hold various class types? Or would I have to make different maps/vectors/arrays/etc. for each type of class?
Yes you can store inherited classes in map, but pointers to them, not objects themselves. Here's a short example (it lacks memory management on pointers)
You may have template on classes and functions, but not on instances.
You should stick to the map to
BaseClass*
'es.First things first:
This is not valid C++ and could only mean something like a
template alias
, but I believe, that is not what you are looking for.Storing polymorphic objects in C++ is complicated by slicing (constructing a value of the base type from a value of a derived type). Dynamic polymorphism can only be handled through references or pointers. You could potentially use
std::ref
orboost::ref
for situations in which the map will only be passed down the callstack, but this requires some care. Often, storing pointers to the base is the way to go:std::map<std::string, base*>
. Managing deallocation yourself is rather tedious and eitherstd::map<std::string, std::unique_ptr>
orstd::map<std::string, std::shared_ptr>
are preferred, depending if you need shared semantics or not.Basic example. Someone should replace this with something more meaningful.
Below is the expansion of solution suggested by anton.