Error when iterating through a vector of an abstract class

0

Using polymorphism I have created a Sofa, Bed and Table class from an abstract class called Item. printDetails() is a virtual function in the Item class and it is redefined for the Sofa, Bed and Table classes. I have also created a class for dealing with vectors of Items called ItemVector. I have populated the Item vector with sofas, beds and tables with the function below

void ItemVector::AddItem() {
    string Answer = "y";
    while (Answer == "y") {
        cout << "Would you like to register a sofa to the warehouse stock (y/n)?" << endl;
        cin >> Answer;
        if (Answer == "y") {
            Sofa newSofa;
            itemVector.push_back(&newSofa);
        }
        else if (Answer != "n") Answer = "y";
    }
    Answer = "y";
    while (Answer == "y") {
        cout << "Would you like to register a bed to the warehouse stock (y/n)?" << endl;
        cin >> Answer;
        if (Answer == "y") {
            Bed newBed;
            itemVector.push_back(&newBed);
        }
        else if (Answer != "n") Answer = "y";
    }
    Answer = "y";
    while (Answer == "y") {
        cout << "Would you like to register a table to the warehouse stock (y/n)?" << endl;
        cin >> Answer;
        if (Answer == "y") {
            Table newTable;
            itemVector.push_back(&newTable);
        }
        else if (Answer != "n") Answer = "y";
    }
}

An error is then thrown with the line containing "(*pos)->printDetails();" in the code below. The error says "Unhandled exception at 0x0038FDAA in Project1.exe: 0xC0000005: Access violation reading location 0xCCCCCCCC."

void ItemVector::DisplayInfo() {
    vector<Item*>::const_iterator pos;
    int i = 0;

    for (pos = itemVector.begin(); pos != itemVector.end(); ++pos) {
        cout << "Item number " << ++i << " has the following details:\n";
        (*pos)->printDetails();
    }

How can I avoid this? I wanted to use a singular vector for all items instead of a separate vector for Sofas, Beds and Tables.

c++
pointers
vector
abstract-class
asked on Stack Overflow May 6, 2021 by Sam

1 Answer

3

Lines like this

{
    Sofa newSofa;
    itemVector.push_back(&newSofa);
}

are bad because non-static local variables like newSofa here are local to this block and is eliminated on exiting from this block. Therefore, you cannot use the pointer after exiting from this block.

Instead of this, you should allocate objects to the heap so that it remains after exiting the block for later use.

It can be done like this:

{
    itemVector.push_back(new Sofa());
}
answered on Stack Overflow May 6, 2021 by MikeCAT

User contributions licensed under CC BY-SA 3.0