Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ?

>Solution :

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
{
    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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading