Exercise 9:

Create a directory ex9 and store in this directory all the files corresponding to this exercise.

Question 1: Private inheritance and composition.

This first question will help you checking your understanding of private inheritance.

Your task is to write a class Car that behaves similarly to the class Car_composition below but use private inheritance instead of composition. The code for the class Car is as follow (file "test_private.cpp"):

// test_private.cpp
#include <iostream>

class Engine {
public:
 Engine(int n) : num_cylinders(n) { 
   std::cout << "Engine with " << num_cylinders 
             << " cylinders" << std::endl;
 }
 void start() 
 { 
    std::cout << "Starting the engine" << std::endl; 
 }

private:
 int num_cylinders;
};

class Car_composition {
public:
 Car_composition() : _e(16) {
  std::cout << "new car with 16-cylinder engine" << std::endl;
 }
 void start() {
  _e.start();
 }

private:
 Engine _e;
};

class Car /* complete the code as specified by the exercise */;


// function to test our classes
int main()
{
  Car_composition composition;
  composition.start();

  Car car;
  car.start();
}
As stated above: your goal is to write a class Car that behaves similarly to Car_composition but uses private inheritance from Engine instead of composition (i.e. instead of having an object of type Engine). Please add your class Car to the file "test_private.cpp" (from above).

Question 2: Exceptions.

This question will test your understanding of how to use exceptions in C++.

You can write all the code in one file: "test_exception.cpp"

Write a class MyException that inherits from runtime_error (which is defined in the C++ standard library). MyException has one constructor taking a string as argument. By default this argument will be equal to "MyException".

Write a function f() returning void and taking no arguments. The only action of f() is to throw an exception of type MyException.

Write and complete the code for a function test_exception() returning void and with no arguments:
void test_exception()
{
  int* array = new int[10];
  for (int i = 0; i < 10; i++) array[i] = i;

  // call f() in a try block
  // then catch potential exception of type MyException
  // be careful to clean memory dynamically allocated 
  // by test_exception()
  
}
You can use the following main function to test your code:
int main()
{
  test_exception();
}
Note: do not forget to put all the necessary headers.