Meeting 04: Static Polymorphism using Templates

Today we will look at how to resue code using polymorphism and specifically static polymorphism through generic programming.

Links:

Exercise 04: How does std::vector work?

The goal of this exercise is 1) to see how to use templates to make code generic and 2) to learn about value semantics. We will see very roughly how the standard library container std::vector is implemented (this should largely be a review of 2574 material).

We will write a templated class called MyVector that holds a dynamically allocated array of items of the type specified by the template parameter. The array grows as needed as we put things into it.

GitHub Invitation URL: exercise04

Prerequisites:

Steps:

  1. Create a working directory somewhere on your computer, then change to that directory.
  2. Clone the assignment for today after accepting the GitHub invitation at the link above.

    git clone https://github.com/VTECE3574/exercise04-USER.git

    where USER is your GitHub username. You will have to enter your GitHub username and password.

  3. Examine the contents of the repository.

    • catch.hpp - this implements one of the testing frameworks we will be using this semester.
    • test_myvector.cpp - this uses catch to define some tests for our vector implementation.
  4. Create a file MyVector.h defining a templated class called MyVector with

    • A default constructor - the vector is empty by default.
    • A destructor
    • A method called size that returns the number of items currently in the vector
    • A method called empty that returns true if there are no items, else false
    • A method called push_back that adds items to the myvector
    • A method called at that returns a reference to the item at a given position, it should throw the exception std::range_error if the position is invalid
    • A method called at that returns a constant reference to the item at a given position, it should throw the exception std::range_error if the position is invalid
  5. Implement the above methods in a file name MyVector.tpp. You can test it compiles and works by compiling the program test_myvector.cpp, which includes the module and defines some tests for it.

  6. Commit the source files to the repository

  7. Implement the following to give MyVector value semantics

    • A copy constructor
    • An assignment operator
  8. Now, use git to commit the source file you changed to the local repository.
  9. Finally, use git push to synchronize the repository with that on GitHub

You have completed the Exercise.