putting a subclass in a pointer to baseclass?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Cyprus106
    New Member
    • Apr 2008
    • 31

    putting a subclass in a pointer to baseclass?

    This is a pretty dumb question to ask, but I'll do it anyways.

    I've got a few superclasses and a subclass. Let's say...

    class BaseFruits {}
    class Apple : public BaseFruits {}
    class Orange : public BaseFruits {}


    Now in my code I've got BaseFruits *currentFruit;

    I THOUGHT that would mean I could stick Apple into currentFruit, but it won't let me, it throws an error saying it can't convert. The problem is I don't want to use dynamic_casts or anything like that because it will never know if it's an Apple, Orange, Grapefruit, whatever... So what do I do? For some reason, I thought since Apple was a subclass of BaseFruits, I could put it in there, but it's been a while since I've messed with this stuff and I figured after 5 frustrating hours Friday and a few more today I should just suck it up and ask for help.

    Thanks!!
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Works for me:
    [code=cpp]
    class BaseFruits {};
    class Apple : public BaseFruits {};
    class Orange : public BaseFruits {};


    int main()
    {
    Apple* a = new Apple;
    BaseFruits* currentFruit = a;
    }
    [/code]

    What are you doing different?

    Comment

    Working...