Can I use polymorphism to store different objects in an array with C++? -


im learning c++, , trying little app. app takes informal ticket (without tax) this:

2 3 mi_primera_tablet 7.95 1 el_general_en_su_laberinto gabriel_garcía_márquez 23.50 

where first line number of items

in second , third line= type of tax + title + price without tax

the items can of different types: books(tax type 3), toys(tax type 1)

all types inherit class article, depending of tax type price different (polymorphism).

i need store items (different types) in array, how can it?

you can store pointers in array.

exapmle (c++11):

#include <iostream> #include <vector> #include <memory>  struct {   int value; };   struct b {   double item; };   class element {  public:   explicit element(a a);   explicit element(b b);    const * asa() const;   const b * asb() const;   private:   class abstractelement {    public:     virtual ~abstractelement() {     }     protected:     abstractelement() {     }   };    template <typename t>   struct concreteelement : public abstractelement {     t body;      explicit concreteelement(t input_body)         : body(std::move(input_body)) {     }   };    std::unique_ptr<abstractelement> element_; };  element::element(a a)     : element_(new concreteelement<a>(a)) { }   element::element(b b)     : element_(new concreteelement<b>(b)) { }   const * element::asa() const {   const auto concrete_element =       dynamic_cast<concreteelement<a> *>(element_.get());   return concrete_element ? &(concrete_element->body) : nullptr; }  const b * element::asb() const {   const auto concrete_element =       dynamic_cast<concreteelement<b> *>(element_.get());   return concrete_element ? &(concrete_element->body) : nullptr; }   int main() {   std::vector<element> values;   values.push_back(element(a{1}));   values.push_back(element(b{1.5}));   values.push_back(element(a{-5}));   values.push_back(element(b{0}));    (const auto & element : values) {     const auto p_a = element.asa();     if (p_a) {       std::cout << "a: " << p_a->value << std::endl;     } else {       const auto p_b = element.asb();       std::cout << "b: " << p_b->item << std::endl;     }   }   return 0; } 

output:

a: 1 b: 1.5 a: -5 b: 0 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

android - Keyboard hides my half of edit-text and button below it even in scroll view -

css - Make div keyboard-scrollable in jQuery Mobile? -