Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C++ Program Program Requirements: Create a class (to be named IntegerList) , to

ID: 3862575 • Letter: C

Question

C++ Program

Program Requirements:

Create a class (to be named IntegerList), to hold integers. Use dynamic memory allocation (smart pointers) for handling any number of integers at run-time (read the integers until a number greater than 3500 is entered).

The member data elements should be private with public member functions to handle the following operations:

Constructor:

with a pointer to an integer as parameter to initialize the class to contain a copy of the integer


Public Member functions:

Add function (AddtoList) to allow the adding an integer at the end of the list

Print function (PrintNum) to display the integers in the List on the standard output

Count function (CountNum) to return the number of integers stored in the list

Explanation / Answer

Dynamic memory

In the programs seen in previous chapters, all memory needs were determined before program execution by defining the variables needed. But there may be cases where the memory needs of a program can only be determined during runtime. For example, when the memory needed depends on user input. On these cases, programs need to dynamically allocate memory, for which the C++ language integrates the operators new and delete.

Operators new and new[]

Dynamic memory is allocated using operator new. new is followed by a data type specifier and, if a sequence of more than one element is required, the number of these within brackets []. It returns a pointer to the beginning of the new block of memory allocated. Its syntax is:

pointer = new type
pointer = new type [number_of_elements]

The first expression is used to allocate memory to contain one single element of type type. The second one is used to allocate a block (an array) of elements of type type, where number_of_elements is an integer value representing the amount of these. For example:

In this case, the system dynamically allocates space for five elements of type int and returns a pointer to the first element of the sequence, which is assigned to foo (a pointer). Therefore, foo now points to a valid block of memory with space for five elements of type int.

  1  2  
  int * foo;  foo = new int [5];  
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote