Multiple class exception thrown: read access violation

  access-violation, c++, exception

In my programming class we are asked to write several classes that represent a store with items.
The class item was supposed to have a name, stock, ID, and price. the file image.h looks like this:

#pragma once
#include <iostream>
#include <string>

class Item {
public:
    Item(std::string name,long ID, int stock, double price);
    std::string getName();
    int getStock();

    std::string _name;
    long _ID;
    int _stock;
    double _price;
};

and I have a support file item.cpp:

#include <iostream>
#include <string>
#include "item.h"

Item::Item(std::string name, long ID, int stock, double price)
    : _name{ name }, _ID{ ID }, _stock{ stock }, _price{ price } {}

std::string Item::getName() {
    return _name;
}

int Item::getStock() {
    return _stock;
}

The class store was supposed to have an array of items as a parameter, and this is what I have for store.h:

#pragma once
#include <iostream>
#include <string>
#include "item.h"

class store {
public: 
    store(Item list[]);
    void printItems();

private:
    Item* _list[];
};

and store.cpp

#include "store.h"
#include <iostream>
#include <string>

store::store(Item list[])
    : _list{ list } {}

void store::printItems() {
    std::cout << "Store:n";
    int i = 0;
    while (i < 100) {
        Item* item = _list[i];
        std::cout << item->getName() << " x " << item->getStock() << "n";
        i++;
    }
}

Also I’m sorry for the lengthy code. I’m new to C++. Here is my main.cpp

#include <iostream>
#include <string>
#include "store.h"
using namespace std;

int main() {
    Item Book{ "Book",1,12,2 };
    Item ColoredPencil{ "Colored Pencils", 13, 14, 15 };
    Item Marker{ "Markers", 123, 50, 24 };
    Item a[3] = { Book, ColoredPencil, Marker };
    store New{ a };
    New.printItems();
} 

I just put random numbers in to test the function. It successfully ran and printed out

Store:
Book x 12

but then it break and threw an exception from image.cpp, line return _stock;:

Exception thrown: read access violation.
this was 0xCCCCCCCC.

It wouldn’t print any information on the next Items. I have spent the past couple hours researching, but I have no idea why the exception was thrown. Any help would be greatly appreciated.

Source: Windows Questions C++

LEAVE A COMMENT