If I have a simple 2 level class hierarchy as, for instance, 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; }
};
I want to have access to the member 'quantity' in the class 'On_hand' using a pointer to the base class 'Spare_part', so I made the 'getQuantity' function a virtual one. The code works fine, however, I have a feeling that I shouldn't have a get/set function (even though a virtual one) to access a member that is defined somewhere down the hierarchy. Is this really considered a bad practice that should be avoided by, for example, redesign of the classes? Edit:The whole hierarchy is a little bit more complex. Alongside the 'On_hand' class there is class for parts available through contracted suppliers. The assumption is that I wouldn't be able to know how many parts are available through the suppliers and that is why 'quantity' is not included in the base class.