Is it considered good practice to define virtual get and set functions in C ++?

If I have a simple hierarchy of level 2 classes, for example this one:

// level 1
class Spare_Part{
private:
    string name;
    double price;
public:
    Spare_Part();
    string getName() { return name; }
    double getPrice() { return price; }
    virtual int getQuantity() { return -1; }; // may also define it as pure virtual
};
//level 2
class On_hand : public Spare_Part{
private:
    int quantity;
    string location;
public:
    On_hand();
    int getQuantity(){ return quantity; }
};

'On_hand', 'Spare_part', getQuantity . , , get/set ( ) , - . , , , ? : . "On_hand" , . , , , "" .

+4
3

, , ; getQuantity Spare_Part, . .

, . is-a, . , , Part_Store, Spare_Part, .

+4

.

, . , , , , , , . .

, , , .

, .

, , , .

, On_hand Spare_Part, , , On_hand Spare_Part. , " " , . , optional<On_Hand> Spare_Part.

, , , -

struct On_Hand_Info { int quantity; string location; };
std::map<Spare_Part, On_Hand_Info> on_hand;

, , - :

struct IRetrievalInformation {
  virtual int getQuantity() const=0;
};

class SparePart{
  string name;
  double price;
  std::unique_ptr<IRetrievalInformation> retinfo;
public:
  Spare_Part();
  string const& getName() const { return name; }
  double getPrice() const { return price; }
  IRetrievalInformation const& getRetrievalInformation() const {
    assert(retinfo);
    return *retinfo;
  }
  IRetrievalInformation& getRetrievalInformation() {
    return const_cast<IRetrievalInformation&>(
      const_cast<SparePart const*>(this)->getRetrievalInformation()
    );
  }
};

class OnHandRetrieval : public IRetrievalInformation {
  int quantity;
  string location;
public:
  On_hand();
  int getQuantity() const final override { return quantity; }
};

PS: , , .

+1

All Articles