Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit

M.Sc. in High-Performance Computing

5614. C++ Programming

Assignment 2

February 24, 2024

Instructions

.  Submit this tar-ball via Blackboard before 1stMar.

.  Gather all your code and pdf/text files into a single tar-ball.

.  Late submissions without prior arrangement or a valid explanation will result in reduced marks.

.  All non-code answers should be submitted in a single pdfor text file.  If you write and scan in, please make sure I can read it!

.  The non-code questions only need short answers - not an essay!

.  Read notes at end of this document.

.  Remember to use comments when appropriate.

Overview of Assignment 2

The assignment is in two parts.  The first part is for you to write a toy example on inheritance.

The purpose of the second part of the assignment is to introduce dynamic polymorphism in C++.

Some of you will be taking the Financial Applications course, but you don’t need to be taking it for the assignment.  The examples here are trivial.  Re- call that the basic principle when using OOP is that your class design should represent the real world problem you are solving.

The second part of the assignment has another toy example where you have a portfolio of three different types of financial instruments that you invested in. All three different types have different payoffs depending on their parameters. So we will have three different classes to represent each type.  Also, because each of the three is-a trade, we will also create a base Trade class.  We can then pass around pointers (or references) to the derived classes as pointers (or references) to the base class.

All of your trades will mature on the same day.  And you want to calculate the payoff from your portfolio, and the profit, given a particular level of the underlying.

Note on comments

10% of available marks will be allocated for comments where appropriate.  Sim- ilar to Assignment 1, please try to use some Doxygen comments.  You can see some basics here http://doxygen.nl/manual/docblocks.html.   Doxygen is more useful for C++ than C. I can show my generated documentation for this code in the next class if you want to see it.  The generated class inheritance diagram for the first part is shown in Fig. 1 and for the second part Fig. 2.

General

The classes in this assignment are trivial.  In real-world code you might follow the rule of zero  for these.  Because this is a assignment for practice, we will add destructors which print simple statements to screen.

It is better to follow the rule of five defaults.  For this assignment make sure to define (either explicitly, or default) or delete each of the five within your classes.

Note that because we mark some member variables as const, that means that the classes cannot be assigned to. So we will delete the assignment operators.

Forward Contract

A forward agreement is an agreement to pay a forward price F  in order to receive the underlying asset at maturity. The payoff is given by

ST  − F                                                      (1)

where ST  is the underlying asset price at maturity.

Call Option

A call option gives the owner the right, but not the obligation, to purchase the underlying asset for a fixed price called the strike prive K.  The payoff from a

max(ST  − K,0)                                               (2)

Put Option

A call option gives the owner the right,  but not the obligation,  to sell the underlying asset for a fixed price called the strike prive K.  The payoff from a put option is given by

max(K ST , 0)                                             (3)

Q1. Makefile (5%)

Write a very simple Makefile to take care of your assignment.  Your file will have five targets:

1. assignment2a

2. assignment2b

3. assignment2b.o

4. portfolio.o

5. clean

(Although you can merge the second and third if you want) Don’t forget to mark clean as a phony target.

make  clean should just delete the executable and any intermediate files.  Don’t forget to mark it as a phony target. You can also add an additional all target which will build assignment2a and assignment2b.

For full marks, use some Makefile variables such as

CXX := g++
CXXFLAGS := −W −Wall −s t d=c++20

Try to use some automatic variables such as $@ and $< in your makefile com- mands. You can use pattern rules if you have covered them elsewhere but you will need to remember to take care of the header file dependencies  (I didn’t cover any pattern rules).

Q2.  Simple Inheritance (20%)

Download assignment2a.cc.  This contains the definition of struct Shape and a main function.  You should not need to change any of these.  Write your own function definitions for struct Cube and struct Cylinder in this file which inherit from Shape. Cube should have a const member variable side and a constructor which takes the length of the side as a parameter.  Cylinder should similarly have radius and height and a constructor which takes these as parameters.

Note 1: If you are having difficulty with the const member variables, it would be better to get it working with non-const than to not submit it.

Note 2:  If you have access to a compiler which supports C++20 then you can access a value for π via std::numbers::pi in the <numbers> header file. Else, you could do something like access M  PI in <cmath>.

Possible output for Q2

s  g++  −o    assignment2a   assignment2a . cc    − Wall   −Wextra   −−std=c++20

s    . / assignment2a

Constructing    Shape    with    volume  =    1.728    and    surface   area  =    8.640 Constructing    Cube    with    side   =    1.200

Side   of    cube :                                                            1.200

Volume    of    cube :                                                      1.728

Surface   area    of    cube :                                  8.640

Constructing    Shape    with    volume  =    181.584    and    surface   area  =   179.448 Constructing    Cylinder    with    radius  =    3.400    and    height =5.000

Height    of    cylinder  :                                        5.000

Radius    of    cylinder  :                                        3.400

Volume    of    cylinder  :                                  181.584

Surface    area    of    cylinder  :               179.448

Destroying    Cylinder    with    radius  =    3.400    and    height =5.000

Destroying    Shape    with    volume  =    181.584    and    surface   area  =   179.448 Destroying    Cube    with    side   =    1.200

Destroying    Shape    with    volume  =    1.728    and    surface   area  =    8.640

Figure 1: Inheritance hierachy for Q2

Q3. Dynamic Polymorphism (30%)

Base class:  Trade

You are given a partially complete definition of the Trade class in instruments.h

class    Trade

{

public  :

//   TODO:

//    (1)    Define    copy    and  move    constructors   as    default

//    (2)    Delete    assignment    operators

Trade ( )   :   cost    {0}{

std  : : cout  <<  ”Trade    ( base    class )    Constructor     ( Default )/n” ; }

Trade    ( const    double    cost )   :   cost    { cost }  {

std  : : cout  <<  ”Trade    ( base    class )    Constructor   ( overloaded )/n” ; }

virtual    ˜Trade    (){

std  : : cout  <<  ”Trade    ( base   class )    Destructor /n” ;

}

//   TODO:

//    (3)    declare    payoff    as    a  pure   virtual     constant    member    function

//    (4)    Grant    access    to    private    member    of    this   class

//                 to    any    non−member    functions    that    need    it

private  :

const    double    cost ;                     ///<   Holds    premium ,   or    cost    to    enter    the    trad

};

You will need to add some lines where TODO is marked in the commments, but you will do this as you are completing the sections below.

The payoff constant member function takes ones parameter, ST , and cal- culates and returns the payoff for that trade at that underlying price.  Declare the function as a pure virtual function.

Figure 2: Inheritance hierachy for Q3

(A) Forward class

Write a class Forward which derives from Trade.  It should have one private member variable   const  double  forward_price    which stores the forward price. You should override the base class payoff function so that, when called, it returns the payoff.  from the contract (See Eq. 1). You do not want to further override this function in more derived classes if you later add any.

Explicitly delete the default Forward constructor.

The constructor which you write will take one parameter which is the forward price.   Forward   (double  fp)  . The forward contracts will have zero cost.

(B) Call class

Similarly, write a class Call which derives from Trade.   It  should have one private member variable   const  double  strike   which stores the strike price. You should override the base class payoff function so that, when called,  it returns the payoff from the contract (See Eq. 2).  You do not want to further override this function in more derived classes if you later add any.

Explicitly delete the default Call constructor.

The constructor which you write will take two parameters - strike price and cost.   Call  (double  cost,  double  k)  .

(C) Put class

Write a third class Put which also derives from Trade. It should have one private member variable   const  double  strike   which stores the strike price.  You should override the base class payoff function so that, when called, it returns the payoff from the contract (See Eq. 3).  You do not want to further override this function in more derived classes if you later add any.

Explicitly delete the default Put constructor.

The constructor which you write will take two parameters - strike price and cost.   Put  (double  cost,  double  k)  .

Q4. Non-member functions (10%)

Download the file portfolio.h which contains two function declarations. You will write the corresponding function definitions in portfolio.cc.

(A) Function to compute portfolio payoff (5)

Write

double    portfolio   payoff ( const    std  : : vector <Trade    const  *>&    trades  ,   const   double    S  T )

which iterates through the container of Trade*, and calculates, and returns, the overall payoff for the portfolio for a given underlying asset price ST .

(B) Function to calculate portfolio profit (5)

Write the function definition for

double     portfolio   profit ( const    std  : : vector <Trade    const  *>&    trades  ,   const    double    S  T )

which calculates the overall profit for the portfolio.

Q5. Putting it all together.  (5%)

The main function is provided in assignment2b.cc.  It is copied below.   Check that it compiles and works as expected.

assignment2b.cc

/* *

*    @ file   assignment2b . cc

*    @brief    Main    function   for    5614    Assignment    2    2024

*    @author   R .   M orrin

*    @version    4.0

*   @date   2024 − 02 − 24

*/

#include  <iostream>

#include  <vector>

#include    ” instruments . h”

#include    ” portfo l io  . h”

in t    main ( )

{

std  : : vector<Trade    const    *>    trades  ;

//   Add   some    trades

trades  . push  back (new    const    Forward   { 6 . 0 } ) ;

trades  . push  back (new    const    Forward   { 2 . 0 } ) ;

trades  . push  back (new    const   Call   {1.0 ,   6 . 0 } ) ;

trades  . push  back (new    const   Call   {5.5 ,   3 . 0 } ) ;

trades  . push  back (new    const    Put   {4.0 ,     7 . 0 } ) ;

trades  . push  back (new    const    Put   {4.5 ,   6 . 0 } ) ;

std  : : cout  <<      ” / n P ortfolio :/ nS  T”   <<    ’ / t ’  <<  ” Payoff ”  <<    ’ / t ’  <<  ” P rofit /n” ; for     ( in t     stock  price  =    0 ;   stock  price  <=    15;  ++stock  price )    {

std  : : cout  <<    stock  price  <<    ’ / t ’   <<    portfo l io  p ayoff ( trades  ,   stock  price ) <<    ’ / t  ’  <<    p o rt fo l i o  p r o fit ( trades  ,   stock  price )  <<  ” /n” ;

}

std  : : cout   <<     /n ’ ;

//    Delete     allocated    trades    manually

for   ( auto   i    =   0u ;   i    <   trades  . s ize  ( ) ;    ++i )    {

delete    trades  [ i  ] ;

}

return    0 ;

}

Sample output using provided main function

Output

>    . / assignment2b

Trade   ( base

class )    Constructor     ( Default )

Constructor

for    Forward    with    forward    price    6

Trade   ( base

class )    Constructor     ( Default )

Constructor

for    Forward    with    forward    price    2

Trade   ( base

class )    Constructor     ( overloaded )

Creating    Call    with Trade    ( base   class ) Creating    Call    with Trade    ( base   class )

str ike     6 .    Premium    paid    1

Constructor     ( overloaded )

str ike   3 .    Premium    paid   5.5 Constructor     ( overloaded )

Creating    Put    with    str ike   7 .    Premium    paid    4

Trade    ( base    class )    Constructor   ( overloaded )    Creating    Put    with    str ike   6 .    Premium    paid    4.5

P o r t f o l i o  :

S - T                 Payoff        P rofit

0                       5                       − 10

1                       5                       − 10

2                       5                       − 10

3                       5                       − 10

4                       6                       − 9

5                       7                       − 8

6                       8                       − 7

7                       11                    −4

8                       15                    0

9                       19                    4

10                    23                    8

11                    27                    12

12                    31                    16

13                    35                    20

14                    39                    24

15                    43                    28

Trade    ( base    class )    Destructor

Deleting    Forward    with    forward    price    2

Trade    ( base    class )    Destructor

Destroying    Call    with    str ike    6

Trade    ( base    class )    Destructor

Destroying    Call    with    str ike    3

Trade    ( base    class )    Destructor

Destroying    Put    with    str ike    7

Trade    ( base    class )    Destructor

Destroying    Put    with    str ike    6

Trade    ( base    class )    Destructor