简体   繁体   中英

Storing Child Class Objects in the Same Container without loosing data?

So lets say I have a base class called Fruits,

class Fruit{

  public TYPE{ Apples, Oranges, Grapes, NoType };
  virtual int getType(){ return Fruit::TYPE::NoType; };
  virtual ~Fruits(){};

  virtual int randomFunc(){ return 991; };

}

And then lets say I have a child class called Apple,

class Apple : public Fruit{

  virtual int getType()override{ return Fruit::TYPE::Apples; };

  virtual int childFunc(){ return -1; };

}

Now, my question, is it possible to receive an object with the base class Fruits, and store various child objects in the same map/container without loosing the 'childFunc()' functionality, or any variables/functions not existent in the base? Ideally I'm trying to find something like,

int FruitStorage::addFruit( Fruit* f, int i ){

     this->fruitsMap[i] = *f; //I feel like receiving a base object will strip the child functionality. 
     return this->fruitsMap[i]->childFunc(); //I need to use the child functions after the object is stored.

}

Would it be possible to use templates for something like this? Is this a practice that's generally frowned upon? My issue with separate containers is that I need to track on a first-in-first-out basis.

Store std::shared_ptr<Fruit> in your container. To see if you can rely on childFunct() you need to do a dynamic_cast<Apple *>(fruit.get()) where fruit is a std::shared_ptr<Fruit>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM