Overview

EXERCISE 18

Modify the measurements program to include the addition code, then using the methods shown, modify the program to enable two objects of type Distance to be multiplied together with the line

dist4 = dist1 * dist2;

INHERITANCE OF CLASSES

We may want to define many types of clock. All our clocks will need the ability to set the time. A digital clock may need seconds adding, an alarm clock may need a bell to be rung.

The problem with this isn't so much the clock class, but what the public in the second class - it's not been defined anywhere, so having it here doesn't make any sense!

class clock
{
  protected:
    int minutes;
    int hours;
  public:
    void AdvMins() { cout << "inline function "; }
    void AdvHours();
};

class digital : public clock
{
  private:
    int seconds;
};

The digital clock has inherited all the characteristics of the base class clock. This will only work if the base class has been altered like this:

class clock
{
  protected:
    // notice private is replaced by protected
    int minutes;
    int hours;
  public:
    void AdvMins();
    void AdvHours();
};

The protected members can be accessed like private members AND also by any class that is derived from this class (e.g. digital).


PROTECTED:

If we need a derived class to have access to the private members of the parent class, we must replace private with protected:

class ClassName
{
  protected:	// can be used by derived classes also
    int StoredValues[50];
    int AmountStored;
  public:
    void SortNums();
    void DisplayVal();
};