Hi,
I have the following code snippets and I get a std::bad_alloc error
where I think there should be none. I've attached the relevant bits of
the base class, derived class and the .cpp file containing the main()
method.
I'd really appreciate any help in getting this error sorted out.
Thanks,
Anuj
Base class:
onst int DESCRIPTION_LEN GTH = 128;
class InventoryItem {
private:
char* itemDescription ;
int itemQuantity;
double itemCost;
void assignDescripti on(const char* desc) {
int stringLength = strlen(desc);
itemDescription = new char[stringLength + 1];
strncpy(itemDes cription, desc, DESCRIPTION_LEN GTH);
}
public:
// Constructor
InventoryItem(c onst char* desc, int qty, double cost) {
assignDescripti on(desc);
itemQuantity = qty;
itemCost = cost;
}
// Destructor
~InventoryItem( void) {
delete [] itemDescription ;
}
}
Derived class:
const int DEFAULT_SIZE = 20;
class InventoryList {
private:
InventoryItem **inventory;
int count;
public:
// Constructor
InventoryList(v oid) {
inventory = new InventoryItem*[DEFAULT_SIZE];
count = 0;
}
// Destructor
~InventoryList( void) {
for (int i = 0; i < count; i++)
delete inventory[i];
delete [] inventory;
}
// Method to add InventoryItem object to InventoryList object
void addItem(Invento ryItem* item) {
inventory[count++] = item;
}
}
Main .cpp:
#include "InventoryItem. h"
#include "InventoryList. h"
#include <iostream>
using namespace std;
int main(void)
{
InventoryList* inventory = new InventoryList[10];
inventory->addItem(new InventoryItem(" wrench", 3, 21.99));
inventory->addItem(new InventoryItem(" hammer", 9, 1.99));
inventory->addItem(new InventoryItem(" pliers", 2, 2.99));
inventory->addItem(new InventoryItem(" saw", 6, 3.99));
inventory->printList();
return 0;
}