I have designed my classes like the below.. I am trying to access unordered_map of derived class from base class pointer pointing to derived class instance... I know I cant do this because of Object Slicing...
I know I can access derived class map after static_casting / dynamic_casting.... --> I am not interested in this approach.
But I am looking for approach in the form of creating abstract base class containing one pure virtual function and defining it in derived class so that it returns a pointer to its map...
I tried using static_cast and dynamic_cast concept It is working but i dont want to do like this.
My Code:
class Base{
public:
Base(string key, string type){
this->key = key;
this->key_Type = type;
}
protected:
string key;
string key_Type;
};
class Derived : public Base{
public:
Derived(string k, string t) : Base(k,t){}
protected:
unordered_map<string, Base*> my_Map;
};
int main(){
Derived *d1 = new Derived("Id","Integer");
Base* b = d1;
Derived *d2 = new Derived("Name","String");
b->my_Map.insert({"Name",d2});
return 0;
}
My expected outcome is somehow i need access to that derived class map so that I can insert values into it like:
my_Map.insert({"Name",PointerobjectofDerivedclass})
EDIT:1-----------------------------
I tried using pure virtual functions, but I am not so clear on how to use this..SO I ended up with a lot of errors..
My code:
class Base{
public:
Base(string key, string type){
this->key = key;
this->key_Type = type;
}
virtual void insertmap()=0;
protected:
string key;
string key_Type;
};
class Derived : public Base{
public:
Derived(string k, string t) : Base(k,t){}
virtual void insertmap(string n , Base* obj){
this->my_Map.insert({n,obj});
}
protected:
unordered_map<string, Base*> my_Map;
};
int main(){
Derived *d1 = new Derived("Id","Integer");
Base* b = d1;
Derived *d2 = new Derived("Name","String");
b->insertmap("Name",d2);
return 0;
}
My compiler errors: In function 'int main()': error: invalid new-expression of abstract class type 'Derived' Derived *d1 = new Derived("Id","Integer"); ^ note: because the following virtual functions are pure within 'Derived': class Derived : public Base{ ^ note: virtual void Base::insertmap() virtual void insertmap()=0; ^ error: invalid new-expression of abstract class type 'Derived' Derived d2 = new Derived("Name","String"); ^ error: no matching function for call to 'Base::insertmap(const char [5], Derived&)' b->insertmap("Name",d2); ^ note: candidate is: note: virtual void Base::insertmap() virtual void insertmap()=0; ^ note: candidate expects 0 arguments, 2 provided