Skip to main contentCal State San Bernardino / [CNS] / [Comp Sci Dept] / [R J Botting] >> [CSci202] >> 07
[Index] [Schedule] [Syllabi] [Text] [Labs] [Projects] [Resources] [Search] [Contact] [Grading]
Notes: [01] [02] [03] [04] [05] [06] [07] [08] [09] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20]
Tue Apr 24 15:10:02 PDT 2007

Contents


    CSci202 Computer Science II, Session 07, Inheritance


      (Previous): C++ Classes [ 06.html ]

      Preparation

      Study this
    1. inheritance::= See http://csci.csusb.edu/dick/cs202/inheritance.html , and
    2. polymorphism::= See http://csci.csusb.edu/dick/cs202/polymorphism.html , and then Chapter 9.

      Write down the questions, doubts, and surprises that you have on a piece of paper.

      Error in Book page 219

      Dynamic Binding is done after the code is compiled, and when the program is running.

      Error in Book Page 330

      In the box it should say
    3. Make sure that all classes have a virtual destructor. (not a virtual constructor).

      Assigned Work Due

      Hand in at least one question, doubt or surprise. Include name and page number.

      Include your printed name! Include a page number!

      Quick Exercise

        There is a company that makes Widgets. It is called "Universal Widgets".

      1. On a blank sheet of paper write your name.
      2. Write the code for a class Widget that has a private integer identifier that is set when a Widget is constructed and has a "getId()" function that returns the id when called.
      3. Sketch you Widget class in the UML on the same piece of paper.
      4. Check your code.
      5. Swap it with some one near you. Check the code you just got. Negotiate any discrepancies.
      6. Now take the other person's work, add your name to it, and write a new class called Wodget that is just like a Widget accept that it has a (private) number of knobs, and has an operation "void add()" to add a knob to the Wodget, and a function "int getKnobs()". DO NOT CHANGE Widget in any way. DO NOT copy any code in Widget.
      7. Hand back the paper with both classes for the first person to review and correct.

      UML Generalization and C++ Derivation

      Notation shown on board.
    4. A Widget generalizes a Wodget.

      Input

        Inheritance: Don't reinvent the wheel.

      1. inheritance::= See http://csci.csusb.edu/dick/cs202/inheritance.html

        What is inherited?

        Exercise/Demo showing what functions and attributes can be inherited... [ 07ex.cpp ]

        Constructors and Inheritance

        Names do not change when inherited so constructors can not be inherited. There is a syntax to explicitly call the right Base constructors.

        Destructors and inheritance

        See below....

        Protected Members

        Only if you have to.... [ 07ex2.cpp ]

        Protected and private inheritance

        My advice: don't. Always inherit "public". It is better to rethink the hierarchy in some way, in my humble opinion than create objects that are both "a special kind of" and also "don't behave the same as"!

        Reuse

        See first example and future labs.

        Polymorphism: Make the computer do the work.

        Notes:
      2. polymorphism::= See http://csci.csusb.edu/dick/cs202/polymorphism.html

        Examples: [ poly1.cpp ] [ poly2.cpp ] [ poly3.cpp ] [ poly4.cpp ] [ poly5.cpp ] and [ polystud.cpp ] [ polystud2.cpp ] [ polystud3.cpp ]

        Also [ 07ex2.cpp ]

        In the UML everything is polymorphic and all operations are "virtual".

        Type identifiers and dynamic casting

        Useful when you are given general objects (or pointers and references to general objects) but you need a object in one of the special kinds of class.

        Destructors should be virtual

        Do it!

        Abstract classes

        Crazy notation? I think so... but this dates back to when virtual functions were implemented by the compiler as a pointer to the code, and 0 indicates the NULL pointer!

        UML notation: Italics. Or write "{abstract}" in the class.

        Notes:

      3. abstraction::= See http://csci.csusb.edu/dick/cs202/abstraction.html

        Interfaces (important but not named in C++ or the book)

        An interface is an abstract class with no attributes and all abstract functions. It defines a family of similar class.

        UML lollipop notation for interfaces.

        Multiple inheritance of several interfaces is a safe and powerful technique used a lot in Java.

        Virtual operators.... tricky

        Multiple Inheritance

        Avoid!

        Exception: OK to inherit and so implement any number of interfaces. Example if time.

      Questions

        One will be answered, at least, from each person. Some in class, some on paper, and some will be recorded here before the next class.

        What are polymorphic classes?

        Classes are not polymorphic in C++, it is the inheritance of virtual functions that is polymorphic.

        Explain public vs private vs protected

        A member in a C++ class can be accessed by only other members in the class (private), or by the class and those derived from it (protected), or from any where in the program (public). The first is safest. The last is most convenient. Don't forget that most software is fragile because programmers took the convenient solution.

        What is the difference between protected and private?

        A protected member is private to all classes except those that are derived from it. For example the function bad() in [ 07ex3.cpp ]
      1. tries to access Alpha::a inside Beta.... and can not do this until the 'private' in Alpha becomes 'protected'.

        Why make a function virtual

        If you do then your pointers and references will work like the objects they point at, rather than the class they appear to point at.

        The classic structure has a class

         		class Derived : public Base {....};
        and the program has a pointer to the Base:
         		Base * pb;
        which is then attached to a Derived object:
         			pb = new Derived (....);
        Now if 'v()' is a virtual function
         			pb->v();
      2. executes "Derived::v()".

        But if "f()" is not virtual then the command executes "Base::f()".

        As a rule we nearly always need pointer to work like the things they point at. (Think demo with magic wand in class). SO virtual gives fewer surprises.

        In my opinion you should make all functions virtual (except in toy programs). My evidence -- Java.

        Notice the above example of the

      3. Aim High pattern of declaring pointers to the most general class.... even if their values are the addresses of low-level special objects.

        If a function is virtual in a base class must it be declared as virtual in a derived class

        No.

        What is the difference between static and dynamic binding

        Binding attaches meaning to identifiers.... if done before the program starts to run, and never changed, then we say the binding is "static". Otherwise we say it is "dynamic".

        For example the value of a variable has dynamic binding. A constant has a static bound value. The length of an array is statically bound. Data members in a class are statically bound. And the type of a variable is bound by the compiler -- statically.

        Virtual functions are bound by the running program.

        As a rule dynamic binding is slower, more powerful, and more popular.

        How can you declare a nested class inside another

        Very easily in C++. Indeed we will have a classic example where we define a nested class and make it private as a helper to a main class:
         class List{
         	private:
         		class Node { public: int data; Node * next };
         	...
         };//end List
        Outside (if it was public) it would be called "List::Node".

        By the way -- Java 5.0 does have nested classes!

        What are static members

        A static member belongs to a class, not to any of the objects in the class. They all share the static member.

        By the way -- the word "static" is abused in C++.

        A classic example is keeping a count of all the objects that are constructed. The static data member

         		static int count;
        is declared and each constructor includes "count++" and each destructor "count --". After the class declare
         		int Class::count = 0;
        and the class will know how many instances have been created..

        I had another variation when I wanted to be sure that every object had a unique identifier. I used a static int to keep track of the last identifier I had used....

        Static functions can be useful when we don't know what object to work with, or when the object has to be constructed. In fact every constructive in a class is static already. But I had a couple of example recently -- what object should handle a Student login? Problem I can't give this responsibility to a Student until I find the Student concerned. So I decided to make the class as a whole search the students for the correct student Id.:

         	static Student * find ( string name );
        So I could have code like this:
         		string name, passwd;
         		cout << ....
         		cin >> name >> passwd;
         		Student * student = find(name);
         		if( !student) error("no such student");
         		else {
         			.... * student ...
         		}

      . . . . . . . . . ( end of section Questions) <<Contents | End>>

      Exercises


      1. Draw UML diagram of C++ classes

      2. Given classes and code: judge if statements will compile or not. [ 07ex.cpp ]
      3. Given classes and code: predict what the output will be. See another_program() in [ 07ex.cpp ]

      4. 25 T/F questions on C++ classes [ 07tf.html ]

      Lab

      [ lab04.html ] TBA where you will create a safe array class.

    . . . . . . . . . ( end of section CSci202 Computer Science II, Session 07, Inheritance) <<Contents | End>>
    (Next): Object Oriented Modeling and a quiz on C++/UML classes, see [ 08.html ] for details.

    Prepare for the Quiz

    Review this page plus [ inheritance.html ] [ polymorphism.html ] [ abstraction.html ] [ 08.html ]

    Abreviations

  1. TBA::="To Be Announced", something I have to do.
  2. TBD::="To Be Done", something you have to do.
  3. Dia::="A free Open Source Diagramming tool for Linux, Windoze, etc. ".

End