Today we will look at how to resue code using polymorphism and specifically static polymorphism through generic programming.
Links:
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:
Exercise 01: Setup
and have a working compiler.Steps:
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.
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.Create a file MyVector.h
defining a templated class called MyVector with
push_back
that adds items to the myvectorat
that returns a reference to the item at a given position, it should throw the exception std::range_error
if the position is invalidat
that returns a constant reference to the item at a given position, it should throw the exception std::range_error
if the position is invalidImplement 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.
Commit the source files to the repository
Implement the following to give MyVector value semantics
Finally, use git push to synchronize the repository with that on GitHub
You have completed the Exercise.