[Skip Navigation] [CSUSB] / [CNS] / [Comp Sci & Eng Dept] / [R J Botting] / [CSci202] / 09
[Text Version] [Syllabus] [Schedule] [Glossary] [Resources] [Grading] [Contact] [Question] [Search ]
Notes: [01] [02] [03] [04] [05] [06] [07] [08] <09> [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20]
Labs: [01] [02] [03] [04] [05] [06] [07] [08] [09] [10]
Mon May 4 12:31:06 PDT 2009

Contents


    CSci202 Computer Science II, Session 09 Polymorphism


      (previous): Inheritance [ 08.html ]

      Polymorphism: Make the computer do the work.

      Notes:
    1. polymorphism::= See http://cse.csusb.edu/dick/cs202/polymorphism.html

      Example code

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

      Also [ 07ex2.cpp ]

      Preparation 13 Object-Oriented Programming: Polymorphism 693

    2. 13.1 Introduction 694
    3. 13.2 Polymorphism Examples 696
    4. 13.3 Relationships Among Objects in an Inheritance Hierarchy 697
      • 13.3.1 Invoking Base-Class Functions from Derived-Class Objects 697
      • 13.3.2 Aiming Derived-Class Pointers at Base-Class Objects 705
      • 13.3.3 Derived-Class Member-Function Calls via Base-Class Pointers 706
      • 13.3.4 Virtual Functions 708
      • 13.3.5 Summary of the Allowed Assignments Between Base-Class and Derived-Class Objects and Pointers 714
    5. 13.4 Type Fields and switch Statements 715
    6. 13.5 Abstract Classes and Pure virtual Functions 715
    7. 13.6 Case Study: Payroll System Using Polymorphism 717
      • 13.6.1 Creating Abstract Base Class Employee 719
      • 13.6.2 Creating Concrete Derived Class SalariedEmployee 722
      • 13.6.3 Creating Concrete Derived Class HourlyEmployee 724
      • 13.6.4 Creating Concrete Derived Class CommissionEmployee 727
      • 13.6.5 Creating Indirect Concrete Derived Class 729 BasePlusCommissionEmployee
      • 13.6.6 Demonstrating Polymorphic Processing 731
    8. 13.7 (Optional) Polymorphism, Virtual Functions and Dynamic Binding “Under the Hood”
    9. 13.8 Case Study: Payroll System Using Polymorphism and Runtime Type Information with Downcasting, dynamic_cast, typeid and type_info
    10. 13.9 Virtual Destructors
    11. 13.10 (Optional) Software Engineering Case Study: Incorporating Inheritance into the ATM System
    12. 13.11 Wrap-Up

      Polymorphism and the UML

      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:

    13. abstraction::= See http://cse.csusb.edu/dick/cs202/abstraction.html

      Interfaces -- an important idea not named in C++ )

      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. , Assigned work Study this page and the reading above.

      Do this exercise [ 09polytf.html ] to review your knowledge.

      Submit a Question before 10am.

      Chapter 13 pages 687 -- polymorphism

      What exactly is polymorphism and how is it used efficiently?

      Polymorphism means: many shapes. It implies shape-shifting.

      It means that when you point at your dog and call it... it comes, but your cat responds by taking a message and thinking about it.

      Based on three things: Inheritance Hierarchy, Pointer declared to point at any class in the hierarchy, and is always attached to one of the specific types.

      In C++ the mechanism that makes it work is pretty efficient any way. You might as well always set it up.

      Chapter 13 pages 696 -- polymorphic

      Does polymorphic take a program straight to the point?

      Yes:-)

      Chapter 13 pages 707 -- Relationships Among Objects in an Inheritance Hierarchy

      Can you further explain the term downcasting and when its best suitable to use as well as the virtual function.

      I avoid explicit "downcasting", if possible. It means that you've got a pointer to an object, and you know more about the object's type than the pointer does.... so you "cast" the object and force the program to treat it as if it was the more specific type of object.

      Chapter 13 pages 708 -- polymorphism

      Can you explain the purpose of making a function virtual?

      To make programs more flexible. To delay decisions and simplify code.

      Chapter 13 pages 709 -- binding and virtual functions

      Could you explain dynamic, late, and static binding?

      We do a whole session in CSCI320 on this! Quick summary.

      A binding is a connection between an identifier and a property. Example: The value of a variable. The meaning of 'int'. The type of a variable.

      A binding is static if it is decided before the program starts and can not be changed. The meaning of 'int' and the types of a variable are both statically bound. Another example: how normal member functions are called.

      Dynamic binding can occur at any point in the program and can be changed at any time. For example: the value of a variable.

      Late binding is a very special kind of dynamic biding that occurs between a pointer to any object and the member functions of that object.

      Chapter 13 pages 732 -- Polymorphism

      Is there a situation where downcasting would be necessary or does this go in the category of Friends and Arrays "Possibly useful but bad practice"?

      If I had to create a hierarchy of evil programming it would start with: char*, arrays, do-while, switch, friends, downcasting, ...

      But that is my personal opinion. Not on any quizzes or finals.

      Chapter 13 pages 696 -- Polymorphism

      Can you show a program with a Polymorphism and how it works?

      See below.

      Chapter 13 pages 697-704 -- Polymorphism

      Can more or demonstrate assigning address of the derived objects and pointers of derived class at base class objects.

      Quick tour simplified examples: [ poly1.cpp ] [ poly2.cpp ] [ poly3.cpp ] [ poly4.cpp ] [ poly5.cpp ]

      Chapter 13 pages 708 -- Virtual Functions

      can you give us an example oh how to use a virtual function?

      Above and in the lab!

      Chapter 13 pages 708 -- Virtual Functions

      Can you give a clearer explanation of virtual functions?

      My opinion: stupid choice of a name and a default.

      Key property -- when you point at an object and send it a message then the interpretation of the message depends on the object not the pointer.

      Chapter 13 pages 708 -- virtual function

      This function uses draw, when else is that used?

      Any time the behavior depends on the type of object. For example, with shapes, calculating the area of the shape depends on the type of shape. A square and a circle have different formulas for area.

      More in lab05.

      Chapter 13 pages 708 -- Virtual Functions

      What is the difference between how virtual and non-virtual functions are called?

      They are called in exactly the same way as all other member functions.

       		object.name(data)
       		pointer->name(data)
      What the code above means changes if the function is virtual. But only in the second form above. The first form is unaffected.

      When the compiler sees this kind of call

       		pointer->virtualFunction(data)
      it inserts some extra code that, when the code executes, it finds the right function for the object the pointer is referring to. This is polymorphism.

      All the other calls are done the normal way. The compiler precalculates which function to call.

      The polymorphic call in C++ uses a vtable.... and you can, if you wish, look this up in the book. It helps some people to look "under the hood".

      Chapter 13 pages 708 -- override

      Is overriding functions safe or does it lead to possible complications?

      Yes.

      Both.

      Chapter 13 pages 708-713 -- Virtual Functions

      How do you declare and use virtual functions to effect polymorphism?

      (1) set up an inheritance hierarchy.

       		class D : public B {......};

      (2) add the word "virtual" to the functions in the base class (B).

       		virtual Type v(....) ;

      (3) use pointers to the higher classes that are attached to objects in the lower class.

      		B* p = new D(...);

      Botting's advice: Aim high.

      Chapter 13 pages ppp-ppp -- Object Oriented Programing : Polymorphism

      can you discuss the problems of programming with switch logic? and why polymorphism can be an effective alternative to using switch logic?

      See below.

      Chapter 13 pages 715 -- switch statements

      Could you explain when and how we use switch statements?

      Switches are part of CS201.... try [ lookup.php?search=switch&from=cs202 ]

      When you use a switch to select different alternatives, you have to list all the alternatives as part of the switch statement. Review the syntax! This means that if you add, delete, or change any alternative then the switch has to be recompiled.

      Further you end up with many switches all over your code. All of them have to be edited and recompiled each time you add, delete, or change the alternatives.

      Polymorphism is done when the program runs -- invisibly where-eve the alternatives are needed. You can add a new alternative -- with out recompiling the original, you can change an alternative, or even delete one quicker and more reliably.

      Chapter 13 pages 697-707 -- polymorphism

      in what other ways does polymorphism help make programing easy

      Polymorphism works the way we think. Send a message and the receiving object knows what to do with it.... With out polymorphism we send a message and the compiler uses the type of the pointer (not the object) to pick the behavior.

      Chapter 13 -- Virtual Functions

      Can you please explain virtual functions, the role they play, where you would use them and why. Also, what is a handle?

      These days all large program use virtual functions and full-blown object-oriented programming. For example in Java -- all functions are virtual!

      Simple example -- writing a program to tell the user a weather forecast.

      In other words polymorphism helps us "rewire" the program at as the program runs.

      The program gains more possibilities.

      A handle is a variable that refers to another object -- it lets us "handle" it from a distance as it were.

      Chapter 13 pages 710-713 -- Virtual Print

      Why does the print function of figure 13.10 print anything even though the print function has not been defined in figures 13.8 or 13.9?

      The implementation files are later in the chapter.

      Multifile programs allow the implementation classes to be written and compiled after the header files.

      Chapter 13 pages 715 -- abstract or concrete

      which is better to use in any situation, an abstract class or a concrete class?

      It depends on the situation.

      First: abstract classes appear higher up the inheritance hierarchy. We always need concrete classes at the bottom. Some people say that all other classes should be abstract..... I'm not so sure.

      Second: you have to ask whether it makes sense for an object to belong to a class -- without belonging to its derived classes. Put differently, when you have several derived classes -- do they exhaust the possible special kinds of base class object? If so then "abstract" is the way to go.

      Third: Over the years we have collected hundreds of ready-to-use Object-oriented patterns that provide good solutions for complex dilemmas by using abstraction and polymorphism. I cover these in CSCI375.

      Chapter 14 pages 715 -- Pure virtual functions

      Can you elaborate a bit on Pure virtual functions?

      See below

      Chapter 13 pages 715-717 -- Abstract Classes

      Does having one pure virtual function make the whole class abstract?

      A single "abstract" function makes a class "abstract".

      We need to be very precise about the terminology.

      A single virtual function does not make a class abstract.

      Just writing the word "virtual" does'nt do it.

      You also have to make the function a pure virtual function by adding "=0;" to the declaration.

       		virtual iAmVirtual(...); // My class may be abstract
       		virtual iAmPureVirtual(...)=0;  // so my class is abstract

      Chapter 13 pages 694-750 -- virtual functions

      Can you elaborate on the functionality of Pure/not pure Virtual Functions and Abstract Classes?

      The effect of making a virtual function "pure" is to stop the program creating any objects of that type. It changes the functionality of the class. You can not use it to declare variables. You can not use it to create pointers to new objects (new Type(data)).

      Chapter 13 pages 735 -- Dynamic Binding

      Can you explain in a less confusing way how Dynamic Binding and vtables work?

      Not really. I will try in class on the board with a simpler example.

      Luckily you can use polymorphism without memorizing vtables and such. And they won't be on the final or a quiz.

      Chapter 13 pages 742 -- Virtual Destructors

      Could you explain virtual destructors a bit more and give an example of it

      A destructor is used to take out the garbage when an object is deleted. By making it virtual you make it more certain that the correct garbage is tidied up.

      So, a simple rule: declare all destructors to be virtual.

    . . . . . . . . . ( end of section CSci202 Computer Science II, Session 10 Input/Output Streams) <<Contents | End>>

    Quizzes to come

    Note the material in this class will be tested in a a quiz in class 12.

    Lab on polymorphism

    [ lab05.html ]

    Next -- templates

    Chapter 14. [ 10.html ]

    Abbreviations

  1. Algorithm::=A precise description of a series of steps to attain a goal, [ Algorithm ] (Wikipedia).
  2. class::="A description of a set of similar objects that have similar data plus the functions needed to manipulate the data".
  3. Data_Structure::=A small data base.
  4. Function::programming=A selfcontained and named piece of program that knows how to do something.
  5. Gnu::="Gnu's Not Unix", a long running open source project that supplies a very popular and free C++ compiler.
  6. KDE::="Kommon Desktop Environment".
  7. object::="A little bit of knowledge -- some data and some know how", and instance of a class".
  8. OOP::="Object-Oriented Programming", Current paradigm for programming.
  9. Semantics::=Rules determining the meaning of correct statements in a language.
  10. SP::="Structured Programming", a previous paradigm for programming.
  11. STL::="The standard C++ library of classes and functions" -- also called the "Standard Template Library" because many of the classes and functions will work with any kind of data.
  12. Syntax::=The rules determining the correctness and structure of statements in a language, grammar.
  13. Q::software="A program I wrote to make software easier to develop",
  14. TBA::="To Be Announced", something I should do.
  15. TBD::="To Be Done", something you have to do.
  16. UML::="Unified Modeling Language".
  17. void::C++Keyword="Indicates a function that has no return".

End