Reputation: 267
my classes
class Product
{
...
};
class Perishable : public : Product
{
public:
int getday();
};
I want to contain a collection of both perishable and product object together and hope to do it by means of a linked list.
Usually for linked list we have something like
class linkedlist
{
struct List
{
int item;
ListNode* next;
}
//.... all the functions
};
but i have a problem here since the data i want to store in item is not an int but either a Product or a Perishable, how do i implement it as a linked list?
Upvotes: 0
Views: 2543
Reputation: 11931
You need Templates. Templates in C++ support generic programming. After declaring template before your class LinkedList you can replace your int item with a T item where T is the place holder and will be substituted for an appropriate data type (custom or primitive) depending upon how you instantiate your object.
Upvotes: 1
Reputation: 73493
You can store the Product*
as an item in the linked list. You should add virtual
methods to the base class Product
which will be dispatched to the appropriate method during run time depending on the actual type of object pointed by this pointer.
Upvotes: 1