I'm trying to build a [base+derived
] class's object container(std::map
to be accurate) which would be a static variable, embedded inside Base class so that every other object either derived from it, or from it's child classes would've only 1 list at most. Also if no object is created, I still would've access to that list through other friendly(static) functions.
Here's the code -
#include <iostream>
#include <string>
#include <unordered_map>
class A{
std::string id;
static std::unordered_map<std::string, A*> list;
public:
A(std::string _i): id(_i){}
static void init(){
// doSomeProcessing or let's just call clear() for now
list.clear();
}
static void place(std::string _n, A* a){
list[_n] = a;
}
virtual void doSomething(){std::cout << "DoSomethingBase\n";}
};
std::unordered_map<std::string, A*> A::list = {};
class B : public A{
std::string name;
public:
B(std::string _n):name(_n), A(_n){}
void doSomething(){std::cout << "DoSomethingDerived\n";}
};
int main() {
A::init();
A::place("b1", new B("b1"));
A::place("a1", new A("a1"));
return 0;
}
The code compiles successfully however, there are two things at top of my mind, which I might be doing wrong, one major and another minor problem.
Major - Pointers as values to std::map
? I'm sure I've totally not grasped them yet, but I'm studying hard. I know they aren't being deleted here, but how should I do it? In the destructor? or let the program finish.....(bad, right?)
Minor - Using static members? I've heard from folks that static variables are bad for some unknown reasons and shouldn't be used unless necessarily required. They were even removed from some early version of cpp. Is that right? But what would be my options then... creating it in main()
.
Any other mistake I might be doing here.
Edit - I'm supplying a sample scenario so to clear my intentions with following example.
Let's say I've an
employee
class and some more specific jobs egeditor
,writer
,developer
that are still derived from employees. However there might exist instance of base classemployee
too, since there might be employees who aren't cateogrised yet, but will be soon.
Let's say this is an requirement, although I'm open to changes. I'm using that static std::map
so that only one instance of it is required which is uniform across all base + derived classes. I'm not so familiar with singleton pattern and such but I'll happily learn it in future.