[ create a new paste ] login | about

Link: http://codepad.org/QUyLRq6l    [ raw code | output | fork ]

johannes - C++, pasted on Aug 31:
class Fruit
{
public:
    Fruit()
        : m_color("fruit-colored"),
          m_peeled(false)
    {}

    virtual ~Fruit() {}
    virtual void eat();    
    virtual void peel();
    void setColor(const std::string &color) { m_color = color; }
    const std::string &color() const { return m_color; }

protected:
    std::string m_color;
    bool m_peeled;
};

void Fruit::eat()
{
    std::cout << "Now eating this " << m_color << " fruit!\n";
}

void Fruit::peel()
{
    if (!m_peeled)
         m_peeled = true;
}

class Orange : public Fruit
{
public:
     Orange()
         : Fruit()
     {
         m_color = "orange";
     }
     void eat();
};

void Orange::eat()
{
    if (m_peeled) {
        Fruit::eat();
    } else {
        std::cout << "Can't eat orange before peeling it!\n";
    }
}

int main()
{
    Fruit *fruit1 = new Fruit;
    Fruit *fruit2 = new Orange;
    Fruit *fruit3 = new Orange;

    fruit1->eat();
    fruit2->eat();

    fruit2->peel();
    fruit2->eat();

    std::cout << fruit2->color();

    delete fruit1;
    delete fruit2;
    delete fruit3;

    return 0;
}


Output:
1
2
3
4
Now eating this fruit-colored fruit!
Can't eat orange before peeling it!
Now eating this orange fruit!
orange


Create a new paste based on this one


Comments: