Home > Software engineering >  Printing variables of different derived class objects inside a single vector
Printing variables of different derived class objects inside a single vector

Time:12-12

So I have this simple code with one base class and 2 derived classes. Each derived class has it's own variable and the base class has an id variable which should be shared with all the elements I create from the derived classes.

After creating 2 objects and adding them in a vector, I can only print their IDs. Is there any way I can get the a and b variables from the corresponding element(s)? (ex: std::cout << items[0]->a;)

class Item
{
public:
    int id;
    Item(int id) { this->id = id; }
};

class ItemTypeA : public Item
{
public:
    int a;
    ItemTypeA(int a, int id) : Item(id) { this->a = a; }
};

class ItemTypeB : public Item
{
public:
    int b;
    ItemTypeB(int b, int id) : Item(id) { this->b = b; }
};

int main()
{
    std::vector<std::shared_ptr<Item>> items;
    items.push_back(std::make_unique<ItemTypeA>(2, 0));
    items.push_back(std::make_unique<ItemTypeB>(3, 1));

    std::cout << items[0]->// I wanna print the a variable but it only lets me print the ID;

    return 0;
}

CodePudding user response:

One of the possible solutions is using virtual functions like in the following example. Take a look for the Print() methods below...

class Item
{
public:
    int id; 
    Item(int id) { this->id = id; }
    virtual void Print(std::ostream& os) { os << id << " "; } 
};

class ItemTypeA : public Item
{
public:
    int a;
    ItemTypeA(int a, int id) : Item(id) { this->a = a; }
    void Print(std::ostream& os) override { Item::Print( os ); os << a << std::endl; }
};

class ItemTypeB : public Item
{
public:
    int b;
    ItemTypeB(int b, int id) : Item(id) { this->b = b; }
    void Print(std::ostream& os) override { Item::Print( os ); os << b << std::endl; }
};

int main()
{
    std::vector<std::shared_ptr<Item>> items;
    items.push_back(std::make_unique<ItemTypeA>(2, 0));
    items.push_back(std::make_unique<ItemTypeB>(3, 1));

    for ( auto& el: items ) { el->Print(std::cout); }
}
  • Related