punksta
punksta

Reputation: 2808

calling the function of derived class c++ from base class

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

Answers (1)

David G
David G

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

Related Questions