I have a question on how to identify an object via a mapped pair, instantiate an object of the type identified with the pair, then store it a container of some sort (likely a vector). The hang up here is that the objects I'm looking for should all be derived classes of some base class.
Here is an example:
class BaseClass {
public:
BaseClass() {cout << "BaseClass constructor...\n"};
~BaseClass() {cout << "BaseClass destructor...\n"};
};
class A : public BaseClass {
public:
A() {cout << "A constructor...\n"};
~A() {cout << "A destructor...\n"};
};
class B : public BaseClass {
public:
B() {cout << "B constructor...\n"};
~B() {cout << "B destructor...\n"};
};
class C : public BaseClass {
public:
C() {cout << "C constructor...\n"};
~C() {cout << "C destructor...\n"};
};
int main(int argc, char *argv[])
{
map <string, BaseClass*> my_map; // Map used to compare a string in order to identify the object type I'd like to make
vector<BaseClass*> keyword_vct; // Vector to store the objects of the different derived class types
BaseClass* ptr;
my_map.insert (make_pair ("A", ptr = new A ));
my_map.insert (make_pair ("B", ptr = new B));
my_map.insert (make_pair ("C", ptr = new C));
string testStr "B";
map <string, BaseClass*> ::const_iterator it = my_map.find(testStr);
if (it == oscards_map.end()) {
cout << "String not found in map." << endl;
}
else {
cout << it->first << "\t keyword found in map!" << endl;
BaseClass* pSomekey;
pSomekey = it->second; // This is where I'm lost
keyword_vct.push_back(pSomekey); // Once I instantiate the derived object in the line above, I want to store it in a container.
}
}
So my main questions are:
How do I make pSomekey into an object of either types A, B, or C?
If I am able to instantiate one of those derived classes, am I able to store these different types of objects into the same vector because that are derived classes of BaseClass?
I notice that when I make the pairs for the map, they seem to construct an object in their respective derived classes.
I also notice that when pSomekey = it->second; is executed, no objects are constructed.
Keep in mind, that this is an example. in my real code, I'm going to be comparing hundreds of testStr to make hundreds of different objects.
Any help or advice would be greatly appreciated. Thanks!