vendredi 23 juin 2017

How to return child class's object when function return type is parent class?

I guess that Java is possible to substitute child class's object for parent class's object. I want to do it in c++.

I'm trying to do it as following. However, I got "error: return type 'Food' is an abstract class" error. How can I fix it?

Before it works:

#include <iostream>

using namespace std;

class Food {
    public:
        virtual void SetPrice(int myprice) = 0;
        int GetPrice() {
            return price;
        }
    protected:
        int price;
};

class Fruit : public Food {
    public:
        void SetPrice(int myprice) {
            price = myprice - 20;
        }
};

class Fish : public Food {
    public:
        void SetPrice(int myprice) {
            price = myprice / 2;
        }
};

int main(int argc, char* argv[])
{
    Food *pFood;
    Fruit myFruit;
    Fish myFish;

    if (strcmp(argv[1], "fruit") == 0) {
        pFood = &myFruit;
    } else {
        pFood = &myFish;
    }

    pFood->SetPrice(100);
    cout << pFood->GetPrice() << endl;

    return 0;
}

After class definition is omitted. it doesn't work:

Food getFoodObject(string type)
{
    if (strcmp(type, "fruit") == 0) {
        Fruit myFruit;
        return &myFruit; // I don't want to write 2 lines. I want to return the above line. This is my another question...
    }

    Fish myFish;
    return &myFish;
}

int main(int argc, char* argv[])
{
    Food *pFood;

    pFood = getFoodObject(argv[1])

    pFood->SetPrice(100);
    cout << pFood->GetPrice() << endl;

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire