Search code examples
c++arraysvirtualderived

Calling a derived function from an array of the base class


How do you call a derived function from an array of the base class?

Ex:

#include <iostream>
#include <string>

class a{

public:
    virtual void prnt(){
        std::cout<<"a"<<std::endl;
    }
};

class b: public a{

public:
    virtual void prnt(){
        std::cout<<"B"<<std::endl;
    }
};

int main()
{
    a array[3];
    array[0] = a();
    array[1] = b();
    array[2] = a();

    array[1].prnt();
}

The output for this example is a.

is there anyway to fix this?


Solution

  • As Justin commented, you're witnessing a case of object slicing. One way to get the behavior you're expecting is to use pointers:

    int main() {
        a* array[3];
        array[0] = new a();
        array[1] = new b();
        array[2] = new a();
    
        array[1]->prnt();
    
        // Don't forget to delete them!
        for (int i = 0; i < 3; ++i) {
            delete array[i];
        }
    }