- You need your base class to have a
virtual
destructor if you should be able to delete
objects through a base class pointer.
- Make
getName
virtual
too.
class Item {
public:
virtual ~Item() = default;
virtual const string& getName() /* const */ = 0;
virtual double getTotalPrice() /* const */ = 0;
};
Note that the Product
class that you aren't allowed to change is slightly flawed.
- It doesn't return values where it should.
- The getter member functions are not
const
.
Suggest some changes if you can't do it yourself:
class Product : public Item {
private: // prefer private member variables
string name;
public:
Product() = default;
const string& getName() const override { return name; }
double getTotalPrice() const override {
// why is this implemented here when there's no price to return?
return {};
}
};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…