Reputation: 2808
How i can call the function of derived class, without typecasting?
base type:
class Fruit{
public:
virtual void show() {cout « "its a fruct" « endl;}
};
child:
class Banana : public Fruit{
public:
void show() { cout « "it's yellow banana" « endl; }
};
array of derived pointers
class Basket
{
Fruit *fructs_;
//...
public:
void show();
//...
};
void Basket:: show(){
for(int i=0; i< index_; i++)
(fructs_+i)->show(); // need call Banana::show here
}
Upvotes: 0
Views: 96
Reputation: 96790
C-style arrays cannot be used polymorphically because of complications with the sizes of the base and derived classes. You should use a std::vector
of Fruit
smart pointers instead:
std::vector<std::shared_ptr<Fruit>> fruits;
Upvotes: 1