I have a program that's setup with a general "item" class, and a "grocery_item" class that inherits the item class. I then have an "array" class that has an array of item pointers(so they can be dynamically bound to other items).
I first overloaded the [] operator for the array class, and it returns an item&. I'm then trying to overload the << operator (only for the grocery_item class, I'll add more later) so i can do: cout << array[i];
But, this isn't working. So my question is:
What's going on here? Is the reason it doesn't work because array[i] returns just a general item and not a grocery_item(or any other type of item as needed)? What can I do so that the right class's overloaded operator is called?
Thanks in advance!
class item
//general item. Will be used for derived items and will use
//virtual functions for the derived classes.
{
public:
item();
virtual ~item();
virtual int add() {return 0;};
virtual int display(){return 0;};
protected:
item * next; //pointer to next item since it will be in a LLL
char * name; //name of the item
};
class grocery_item: public item
{
public:
grocery_item();
~grocery_item();
int add();
int display();
friend ostream & operator << (ostream&, const grocery_item&);
protected:
float cost;
};
class array
{
public:
array();
~array();
item & operator [] (int);
private:
item * list[4];
};
array::array()
{
for (int i = 0; i < 4; ++i)
{
list[i] = new grocery_item;
}
}
array::~array()
{
}
item & array::operator [] (int index)
{
item * temp = new item;
temp = list[index];
return *temp;
}
grocery_item::grocery_item()
{
cost = 0;
}
grocery_item::~grocery_item()
{
}
int grocery_item::add()
{
char temp[40];
cout <<"What is the name of the item? \n";
cin.get(temp, 40, '\n');
cin.get();
name = new char[strlen(temp)+1];
strcpy(name, temp);
cout <<"What is the cost of the item? \n";
cin >> cost;
return 0;
}
int grocery_item::display()
{
return 0;
}
ostream & operator << (ostream & out, const grocery_item & obj)
{
if (!obj.name)
{
out <<"NO ITEM \n";
return out;
}
out << obj.cost << endl;
return out;
}
item::item()
{
name = NULL;
}
item::~item()
{
delete [] name;
}


Sign In
Create Account

Back to top









