Search code examples
c++objectvectorsubclass

C++ Parent class Sub class , working with vector


C++

Hi, so basically I made an Animal Parent class and have Mouse as one of my SubClass.

The Mouse has a unique function (not in the parent class) get_scare :

void get_scare()

In main, I created a vector of Animal Object:

vector<Animal> list_animal

My problem is after Identifying that the subclass mouse is at index i in list_animal, I cannot access my get_scare function. I can only access function in Animal (Parent Class).

How can I access specific functions in mouse, but also keep my vector of Animal.

This is what I did:

if (list_animals[i]->get_animal_name() == "Mouse") {
         
                list_animals[i] -> get_scare(); //Doesn't let me do that

            }

I understand that it does not let me do that since the Object is Animal, How do I go around that!

Thank you!


Solution

  • First of all, you cannot declare vector<Animal> and store a subclass object in it - this is a bug. For example, if you have

    vector<Animal> list_animal(1);
    list_animal[0] = Mouse{};
    

    then any data members of Mouse that are not in Animal are thrown away - this is called slicing.

    But maybe that was just a typo in your question since elsewhere you used list_animals[i]->. Let's assume you declared vector<Animal*> instead. In this case, you can do what you want by using a cast:

    if (list_animals[i]->get_animal_name() == "Mouse") {
        static_cast<Mouse*>(list_animals[i])->get_scare();
        }
    

    This, however, is not a good object-oriented design. A slightly better way, assuming Animal has a virtual destructor (which it should have), is to use dynamic_cast instead of relying on get_animal_name():

    if (auto mouse = dynamic_cast<Mouse*>(list_animals[i])) {
        mouse->get_scare();
        }
    

    This is still not a typical object-oriented design. Normally, you either add get_scare() into Animal, or only use the function when Mouse rather than Animal is available.

    Finally, you have to pay attention to who owns Animal-derived objects. Often you want the vector to own them, in which case you want a vector of smart pointers: vector<unique_ptr<Animal>> or vector<shared_ptr<Animal>>.