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!

5
  • Your second link shows how to define a pure virtual destructor. Commented Oct 28, 2022 at 21:47
  • Pretty sure you could do virtual ~Food() = default; Commented Oct 28, 2022 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? Commented Oct 28, 2022 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. Commented Oct 28, 2022 at 22:28
  • Food still needs to be destructed (to destroy it's members), if its destructor was pure virtual it never could be Commented Oct 29, 2022 at 8:25

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.