Philipp wrote:
> Hello
> This seems a simple question, please send me to the right FAQ if I
> missed it:
>
> If there is a class Fruits with two classes Apples and Bananas extending
> Fruits. Apples has a method called isRed() which returns true if the
> apple is red (Bananas don't have such a method)
>
> Is it somehow possible to make code like this:
> -- pseudo-code --
>
> aMethod(Fruit* aFruit){
> if (aFruit->getClass() == Apples) {
> cout << "Is the apple red?:" << aFruit->isRed() << endl;
> }
> }
You should avoid such situations wherever possible.
>
> Does such a thing as getClass() exist (by default)?
Well, there is typeinfo or dynamic_cast.
> Can I cast aFruit to an Apple pointer and test if the cast is valid?
Yes.
> Is there another nice (and light) way to implement it (except
> implementing getClass() in Fruits and then in each child class)?
aMethod(Fruit* aFruit)
{
Apple* apple = dynamic_cast<Apple*>(aFruit);
if (apple)
{
cout << "Is the apple red?:" << apple->isRed() << endl;
}
}
|