
CArray of different classes derived from common base
I've got this problem here about dealing with derived classes and
arrays. Let's say that my base class is CFruit. I have got a number of
derived classes from CFruit such as CApple, CLemon and CBanana.
I've got a doc/view app using MFC (VC5) and its associated template
classes.
I want to draw each fruit so CFruit has a Draw(CDC* pDC) member
function in it that children classes will override to draw their own
unique fruit. *pDC is passed from my draw function.
Now I have my document and I have a member CArray of CFruit to
represent all of my fruit. However, CFruit should be able to be
anything. So, in essence, I want a CArray that can contain CApple's,
CLemon's and CBanana's. This array needn't know what kind of fruit it
has, only that it is CFruit.
I like this idea in theory because it simplifies my program
significantly. However, the implementation of the idea has stopped me
dead in my tracks. I started up by initializing my array with a few
different kinds of fruit such as CBanana, CApple, and CLemon. This was
fine. Then, in my draw function, I called the Draw function for each
element of the CArray. Instead of magically calling a specific fruit
draw function, it called the CFruit draw function. How can I make the
program call the intended function?
Just for extra detail, CFruit has some basic properties such as weight
and colour and the child classes have different properties such as
bitterness (for CLemon) and bendiness (for CBanana). This means that
these specific details for each fruit kind must be kept whilst in the
CArray.
Thankyou in advance to anyone who replies,
Rodney Lorrimar
Sent via Deja.com http://www.deja.com/
Before you buy.