Week 4 - Polymorphism and Templates

Polymorphism - Classes that can be used as their super classes

  • Whenever we have a student or member of staff we can use them in parameters of person object

  • Abstraction: Encapsulating implementation with private classes - hiding complexity

    • Provides everything a user needs to use the class without needing all the complexity

  • Inheritance: sub classing an object

    • Derived class inherits attributes from base class

    • Public - publicly available outside of class - derived inherits

    • private restricts access to methods and attributes - only accessible in class

    • protected stops access to sub classes

  • Static polymorphism - refers to function overloading resolved at compile time

    • different versions of a method can be defined for different classes in class hierarchy - will be known at compile time

    • Method called is based on static type of object at define time

rectangle is sub class of shape but each has their own draw method
  • Runtime Polymorphism

    • Achieved using virtual functions and inheritance so might not always know whats coming

    • Decision of which function to call is made at run time. e.g. reading shapes from a file would depend on whats in the file

  • Disallowing overriding - final

    • Once method marked as final, no derived class can override it

    • restricts what over people can do with your class

  • (*shapePtr).draw() - will allow me to get access to draw functionality

  • shapePtr→ - different syntax for same thing


Polymorphism in streams

  • in/out are streams - represent the flow of data

    • Streams abstract the details


Templates

  • Java generics - whenever we have algorithm such as sort - allows us to write the code once and have it applied to different types

    • Templates allow us to do same sort of thing

  • Function templates can be called with any type

  • Implementation templates define a specific implementation for a specific type