20-CS-4003-001 Organization of Programming Languages Fall 2016
Virtual functions

Lambda calculus, Type theory, Formal semantics, Program analysis

All lectures
Motivation - virtuals and polymorphism

Instructions for applets:

All applets have a button labeled 'Jar File'. Click to download the jar file. Run it on your laptop either by double clicking it or, on the command line, by executing java -jar virX.jar where virX.jar is the jar file you downloaded.

    Demonstration of virtual functions. Given a hierarchy of classes and an object obj of one of those classes. Cast obj to some level of the hierachy. From there and starting at that point, look up the hierarchy for a method whose prototype matches the method of obj that is invoked. Otherwise look down the hierarchy until reaching the level at which obj was created.
    The method invoked is always in objs class, regardless of cast.
    The method f() is missing from two levels.
    Any future Person type can be handled without fear of the code breaking because there will always be a getRank and setRank method to call.

Class Person is defined as are several concrete subclasses of Person including Vagrant, Student, and Professor. These are intended to be placed into a Vector. Associated with each subclass are methods, declared as virtuals in Person, called setRank and getRank. These operate on data that is known to the subclasses but not the base class. When subclass objects are removed their data types are known only as Person. Since setRank and getRank are virtual, the correct method will always be invoked.

    An interface can substitute for the Person class. Then implementing classes need to keep their own state and need to implement all the specified methods.
    An abstract class can be used as well.