Home > Net >  How to Store and retrieve the the correct Type of DerivedClass Pointer To/From Map of BaseClass Poin
How to Store and retrieve the the correct Type of DerivedClass Pointer To/From Map of BaseClass Poin

Time:08-08

Hello i have question about Maps and Inheritance.
I have Map of BaseClass Pointer:

std::map<int,std::shared_ptr<Game>> GamesByID;

and inserted Derived Class Pointer into it like:

GamesByID.insert(make_pair(ID,std::make_shared<ActionGame>(ID,Title,Metacritic,Recommendations,Price,lvl)));

now i wanted to count how many ActionGame Pointer i had in my map with somthing like that


  for (auto& e : GamesByID)
        {
    if(typeid(e) == typeid(SurvivalGame)){
              count;
            
    }else{
        cout << typeid(e).name() << "  typeid" <<endl;
    }

}

But in the map ther are only BaseClass Pointer, now what is my mistake do i instert them wrong ?

CodePudding user response:

The map contains pointers of type "Game" nothing to do with derived class, the name to store a derived class with a pointer of base class is called polymorphism, You will need a function to return something like a flag to get what type of class it is. What I'm trying to say is that polymorphism will let you create a pointer variable with the type of the base class that can hold the address of a derived class the pointer itself in the map is not a derived class object

class baseClass
{
protected:
    string type = "baseClass";
public:
    string getClassType()
    {
        return this->type;
    }
}
class derivedClass : public baseClass
{
    derivedClass()
    {
        this->type = "derivedClass";
    }
}

Here I gave you an example where the base class has a type variable where you store the type and now if you check the type member of a baseClass* you will get a string telling you the type since both the variable and function to return the variable are in base class

  • Related