My professor gave the following code to show an example of inheritance:
//Base class
class Inventory {
int quant, reorder; // #on-hand & reorder qty
double price; // price of item
char * descrip; // description of item
public:
Inventory(int q, int r, double p, char *); // constructor
~Inventory(); // destructor
void print();
int get_quant() { return quant; }
int get_reorder() { return reorder; }
double get_price() { return price; }
};
Inventory::Inventory(int q, int r, double p, char * d) : quant (q), reorder (r), price (p)
{
descrip = new char[strlen(d)+1]; // need the +1 for string terminator
strcpy(descrip, d);
} // Initialization list
//Derived Auto Class
class Auto : public Inventory {
char *dealer;
public:
Auto(int q, int r, double p, char * d, char *dea); // constructor
~Auto(); // destructor
void print();
char * get_dealer() { return dealer; }
};
Auto::Auto(int q, int r, double p, char * d, char * dea) : Inventory(q, r, p, d) // base constructor
{
dealer = new char(strlen(dea)+1); // need +1 for string terminator
strcpy(dealer, dea);
}
I was confused line “Auto::Auto(int q, int r, double p, char * d, char * dea) : Inventory(q, r, p, d)”, what is the definition “Inventory(q, r, p, d)” doing. Similarly
in the line “Inventory::Inventory(int q, int r, double p, char * d) : quant (q), reorder (r), price (p)” I’m not sure what he is doing with quant (q), reorder (r), price (p). Are these the same variables that were defined in class as int quant, reorder and double price? If so, why did he have to use in the constructor. And why/how did he use a constructor from a base class to help define “Auto” class constructor.
He is using “initialization lists”.
He is calling the base class constructor.
Auto::Auto(int q, int r, double p, char * d, char * dea) : Inventory(q, r, p, d)defines a constructor for theAutoclass which calls the parametrized constructor of theInventory. The parameterized constructor needs to be called becauseAutois inheriting fromInventoryandInventorydefines a parameterized constructor. C++ specifies that if you define a parameterized constructor, the default constructor is overridden and the only way you can instantiate an object of that class or any sub-class is by calling the parametrized constructor (or by defining an alternate default constructor).In the case of
Inventory::Inventory(int q, int r, double p, char * d) : quant (q), reorder (r), price (p), he is initializing the fieldsquant,reorderandpricewith the valuesq,randprespectively. This is actually a shorthand and you can instead assign the values in the constructor body (unless the member is a constant).