0

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
}
punksta
  • 2,738
  • 3
  • 23
  • 41
  • 'Banana' is not a base of 'Fruct' (fructs_+i)->Banana::show(); It will work in the reverse situation(call Fruct method from banana pointer) – punksta Mar 31 '14 at 21:28
  • As it is virtual function, won't it call the derived class automatically? – Neil Kirk Mar 31 '14 at 21:29
  • @NeilKirk look at type of fructs_. Its base-type pointer. – punksta Mar 31 '14 at 21:32
  • 1
    That isn't an array of derived pointers. Its a pointer to one or more *objects*. And you're all-but-guaranteed to encountered a [slicing problem](http://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c) until you understand that. – WhozCraig Mar 31 '14 at 21:34
  • If a fruit pointer, points to a bananna object, calling show on it, will call bananna's function. – Neil Kirk Mar 31 '14 at 21:34
  • @WhozCraig I understand it. The question is not in the method of naming. – punksta Mar 31 '14 at 21:37
  • @StasShakirov Who said anything about *naming* ? The provided code, the dereference through `fructs_+i`, is performing typed-pointer arithmetic on `fructs_` which is of type `Fruits`. If your intent is to have an array of pointers to polymorphic derivations accessed through a common base, that isn't going to do it. – WhozCraig Mar 31 '14 at 21:42

1 Answers1

1

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;
David G
  • 94,763
  • 41
  • 167
  • 253