-1

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?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
WEPIOD
  • 53
  • 9

2 Answers2

0

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];
    }
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0
 array[1] = b();

The above is object slicing.Read about it here

Polymorphism works with pointers and references only.

 a *array[3];
 array[0] = new a();
 array[1] = new b();
 array[2] = new a();

 array[1]->print() 
Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34