Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Printing variables of different derived class objects inside a single vector

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;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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); }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading