L1 Q3 : Writing the four methods for classes

As presented in the lecture you need to write four methods for the classes which do dynamic memory allocation
The four methods are (see lecture slides 8 - 10 - the Example class)

  • constructor
  • copy constructor
  • = operator overloading
  • destructor

You know you are using dynamic memory allocation whenever you use new and delete in your classes to allocate memory to arrays or pointers.

For simple classes which you have written like Square, Circle and Student there is no dynamic memory allocation being done. For such classes only the constructor or default constructor is sufficient. However if you are allocating memory to arrays and using pointers then you are doing dynamic memory allocation and you need to write the three additional methods other than the constructor otherwise you may have problems in your C++ programs.

Exercise 1: Write a class CheckoutCalculator which behaves somewhat like the machine at the checkout counter in supermarkets. This calculator should ask for the number of items for which the total is to be calculated and then allow you to enter the price for every item. After entering all the items it displays all the prices entered and the total amount.
Here you need to use dynamic memory allocation since you do not know how many items will be there. Use an array to store the prices of items. Solution
The output of the program should look like this (for example)

Enter the number of items to enter:5
enter price for item 1:2
enter price for item 2:3
enter price for item 3:1
enter price for item 4:2
enter price for item 5:2
price for item 1:2
price for item 2:3
price for item 3:1
price for item 4:2
price for item 5:2
Total:10

Exercise 2: Write a class Results which stores all the results in an array. Assume that we need to store only the results of a single semester which is four results. Each result will be final marks for a course between 0-100 and is stored in an integer array. Use dynamic memory allocation and the four methods mentioned above. Add separate methods to calculate the total marks for all courses and the average marks. Add a field for student ID. Solution

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License