0

I am learning Object Oriented programming. Here is a simple code snippet that I have written:

class Food {
protected:
    int id;
    FoodTypes type;
    string name;

public:
    Food(int id, FoodTypes type, string name) {
        this->id=id;
        this->type=type;
        this->name=name;
    }
    virtual ~Food() = 0;
};

class Dish: public Food {
protected:
    double cost;

public:
    Dish(int id, FoodTypes type, string name, double cost) : Food(id, type, name) {
        this->cost=cost;
    }
    void display() {
        cout<<id<<" "<<type<<" "<<name<<" "<<cost<<"\n";
    }
    ~Dish() {}
};

I get the error:

/tmp/ccW3e3PZ.o: In function 'Dish::~Dish()': main.cpp:(.text._ZN4DishD2Ev[_ZN4DishD5Ev]+0x25): undefined reference to 'Food::~Food()'

Based on the solution mentioned here, I need to define the destructor of my base class (~Food), but IMO I cannot do that since I need it to be a pure virtual function (as suggested here). If not for the destructor, there's no other function within the base class that can be delegated to be pure virtual (and the base class would no longer be abstract/interface).

So how do I resolve the error? Thanks!

  • Your second link shows how to define a pure virtual destructor. – HolyBlackCat Oct 28 '22 at 21:47
  • Pretty sure you could do `virtual ~Food() = default;` – S3gfault Oct 28 '22 at 21:49
  • @fabian, oh, I see, we cannot use `=0;` for declaring a pure virtual destructor of a base class (we need to actually define it with an empty body instead). Am I correct? – R Karandikar Oct 28 '22 at 21:50
  • 1
    `pure virtual` doesn't mean it _doesn't_ have an implementation. All pure virtual functions _can_ have an implementation. Additionally a `pure virtual destructor` *must* have an implementation. – Mike Vine Oct 28 '22 at 22:28
  • `Food` still needs to be destructed (to destroy it's members), if its destructor was pure virtual it never could be – Alan Birtles Oct 29 '22 at 08:25

0 Answers0