Lecture 3. Inheritance

Objective: In this lecture unit, we show:

3.1 Inheritance Basics

3.2 Types of Inheritance

                       =============================================
                       Inheritance    Base Class      Derived Class
                          Type      Member Access     Member Access
                       =============================================
                                        public           public
                          public       protected        protected
                                        private          private
                       ---------------------------------------------
                                        public          protected
                         protected     protected        protected
                                        private       (inaccessible)
                       ---------------------------------------------
                                        public           private
                          private      protected         private
                                        private       (inaccessible)
                       ---------------------------------------------

3.3 Types of Inheritance (Example)

Mark each of the following numbered statements as legal (Y) or illegal (N):

class A
{
public:
   int aPubVar;

private:
   int aPrivVar;

protected:
   int aProtVar;
};

class B : public A
{
public:
   int bPubFunc();
   int bPubVar;

protected:
   int bProtFunc();
   int bProtVar;
};

class C : protected B
{
private:
   int cPrivFunc();
};

int B::bPubFunc()
{
     ...
(1)  aPubVar  = 0;
(2)  aPrivVar = 0;
(3)  aProtVar = 0;
     ...
}

int C::cPrivFunc()
{
     ...
(4)  aPubVar  = 0;
(5)  aPrivVar = 0;
(6)  aProtVar = bProtFunc();
     ...
}

main()
{
     ...
     C cObj;
(7)  cObj.aPubVar  = cObj.bPubFunc();
(8)  cObj.aProtVar = cObj.bPubFunc();
(9)  cObj.bPubVar  = cObj.bProtFunc();
(10) cObj.bProtVar = cObj.bProtFunc();
     ...
}

3.4 Adding Members

C++ defines in <stdexcept> the class exception. There areseveral kinds of exceptions, including bad_alloc and bad_cast. They are derived classes of exception. All exception classes have the what method which can be used to return a (primitive) string that details an error message.

Object& operator[](int index)
{
   if (index < 0 || index >= size())
   {
      throw BadIndex(index, size());
   }
   return objects[index];
}

class BadIndex : public exception
{
public:
   BadIndex(int idx, int sz) : index(idx), size(sz) {}

   int getIndex() const { return index; }
   int getSize()  const { return sz; }

private:
   int index;
   int size;
};

int main()
{
   NewVector v(10);

   try
   {
      for (int i = 0; i <= v.size(); i++)
         v[i] = 0;
   }
   catch(const BadIndex& e)
   {
      cout << e.what() << ", index=" << e.getIndex()
           << ", size=" << e.getSize() << endl;
   }
   return 0;
}

3.5 Overriding a Method

3.6 Static and Dynamic Binding