I can't seem to get my inheritance to work correctly. I have multiple classes each with their own inheritance. The base class is a Plant. A plant has two subclasses, tree and flower. The flower then has rose and tulip. The plant class has a function which sets the age, which is a private variable. I am trying to initialize a rose then set it's age but am getting error: request for member ‘setAge’ in ‘rose1’, which is of non-class type ‘rose()’
I have made sure to include the flower.h in the rose.h and the plant.h in the flower.h files. I have also done the class rose : public flower and class flower : public plant in the respective header files.
I have now come across another problem, which is more with pointers. I have added the rose, tulip, oak, and elm to a queue of plants by passing in a pointer to a plant, I'll post the code below. But now when I dequeue the item, I cannot tell which type of plant it was. How can I do this without storing what type of plant it is? We were told not to store the name of the plant.
void Queue::enqueue(const QueueItemType& newItem)
throw(QueueException)
{
try
{ // create a new node
QueueNode *newPtr = new QueueNode;
// set data portion of new node
newPtr->item = newItem;
newPtr->next = NULL;
// insert the new node
if (isEmpty())
// insertion into empty queue
frontPtr = newPtr;
else
// insertion into nonempty queue
backPtr->next = newPtr;
backPtr = newPtr; // new node is at back
}
catch (bad_alloc e)
{
throw QueueException(
"QueueException: enqueue cannot allocate memory.");
} // end try
} // end enqueue
I'm stumped, so any ideas would be greatly appreciated!
Thanks,
Chris
edit: all the queue code is correct, it was given to us by our teacher
1 2 3 4 5 6 7 8 9 10 11 12
void Queue::dequeue(QueueItemType& queueFront)
throw(QueueException)
{
if (isEmpty())
throw QueueException(
"QueueException: empty queue, cannot dequeue");
else
{ // queue is not empty; retrieve front
queueFront = frontPtr->item;
dequeue(); // delete front
} // end if
}
when I dequeue the item, I cannot tell which type of plant it was.
You shouldn't need to, unless you're studying RTTI. It's more likely that you're studying inheritance (hopefully interface inheritance). Just use the pointer or reference to plant that you obtained and call its virtual functions -- if the plant is really a rose, rose's functions will be actually called.