I am trying to create a map of static objects map<string, base*>
, where base
is derived by classes class1
and class2
. My map will store pointers to objects of type class1
and class2
.
After reading a few posts I decided to do this by creating a singleton with a static class function to initialize the map:
class A { // singleton class
public:
static map<string, base*> create_map() {
map<string,base*> m;
m["1"]=new class1();
m["2"]=new class2();
};
static const map<string, base*> myMap;
};
int main() {
const map<string,base*> A::myMap = A::create_map();
myMap["1"]->func();
}
However this gives an error: myMap is not declared in this scope
. Can somebody explain the singleton method and what I am doing wrong. How would this change if I have a separate header file ?
TIA.
EDIT: Changed the code to:
class A { // singleton class
public:
static map<string, base*> create_map() {
map<string,base*> m;
m["1"]=new class1();
m["2"]=new class2();
return m;
};
static const map<string, base*> myMap;
};
const map<string,base*> A::myMap = A::create_map();
int main() {
A::myMap["1"]->func();
}
This still gives an error: passing const std::map<std::basic_string<char>, base*> as 'this' discards qualifiers.