SlideShare a Scribd company logo
Assg 07: Templates and Operator Overloading
COSC 2336 Spring 2019
Dates:
Due: Thursday March 07, by Midnight (note the di�erent due
date)
Objectives
� Practice creating a more realistic abstract data type ADT
� Using operator overloading to do output, insertion and access
into a
list.
� Use templates so our ADT can hold objects of any type
Description
In this assignment you will be practicing operator overloading. I
will also,
for extra credit, give an additional task to convert your class
into a class
template, so that it will work as a container for any type.
In this assignment you will be expanding on / creating a new
version of
the ListType data type we have seen examples of before in
class. Your task is
to create a ListType that holds a list of integers. You will be
asked to create
several member functions, and then to create several overloaded
operators
for your list of integers. Your basic task is to user operator
overloading to
support appending and prepending to a list, outputting the list
as a string
and to an output stream, accessing the list (using the indexing
operator[]),
and concatenating lists together (using operator+).
I have given you a starting template for your ListType that
already
contains 3 versions of the class constructor. I have also already
provided you
the operator= implementation, to provide the copy operator for
your class.
You should �rst get your class to work as a simple ListType
that holds a
list of integers. If you get your class working for integers and
submit it, you
1
can then turn your class into a template class, so that your list
can work on
objects of any type. I will give up to 10 bonus points for
implementations of
working class templates, if you �rst mostly have your basic
ListType working
for simple integers. As usual I have also given a �le with a
main function
and a lot of commented out tests. You should implement the
class member
functions in the order speci�ed next, commenting out each test
one at a time,
to incrementally develop and test your ListType class
implementation.
For this assignment you need to perform the following tasks.
1. As mentioned in the starting template I have given you a
starting class
de�nition, some class constructors and the destructor, and the
copy
operator=. You �rst need to write two simple getter methods in
order
to access the size and allocSize class member values. These
should be
called getSize() and getAllocSize() respectively. These
functions
should be class const functions (you guarantee that calling them
will
not cause the class to be modi�ed. These functions take no
parameters
as input. They both return an int value, because the size and
allocSize
member parameters are both integer values.
2. Write a function called tostring(). This function will be a
const class
function (the class is not modi�ed when it is called). This
function
takes no parameters as input, and it returns a string. We use this
function in our testing, so you need to get it correct, but you
have
implemented versions of this type of function in previous
assignments.
The function should only create a string of the items currently
in the
list. So it will return a string like "[3, 5, 4, 2]" if those are the 4
items
currently in the list. See the test code for speci�cs.
3. Overload the operator<<() to provide the ability for the
ListType
class to be output to a stream. This will be a friend function,
and again
it will be pretty similar to several examples we have seen of
overloading
the output stream operator. You should use the tostring()
method
in this function, but it outputs additional information, such as
the id,
size and allocSize of the list to the output stream.
4. Create a function named appendItem(). This function takes an
int
value as its only parameter, and it does not return a value. The
indi-
cated integer value should be appended to the end of your list
when
this function is called. You need to correctly handle causing the
size of
your memory allocation to grow if needed in this function, if
your list
is currently using all of the allocated memory. Once this is
working,
2
overload the operator&() operator. We will de�ne the &
operator to
mean list appending. For example, if you do list & 5 it will
cause 5
to be appended to the end of the list (assuming list is a variable
of List-
Type). This function will simply call appendItem() to do the
work,
the only di�culty is getting the syntax correct to declare you
are over-
loading the operator. This is not a friend function, like
operator<<().
Read our textbook about binary operators to see examples of
how to
overload a binary operator like this as a member function of a
class.
5. Create a function name prependItem(). This works the same
as the
append, but it prepends the indicated integer parameter to the
front
of the list instead of to the end. However, you still need to
check and
grow your allocated memory before prepending if your list is
currently
full. Also prepend is a bit more complicated, because since we
are
implementing an array based list, you need to shift all of the
current
items 1 index up in your items before you can prepend to the
beginning
of the list. We will also overload the operator|() for our class to
represent prepending an item. Thus if you do list | 5 this will
cause
5 to be prepended to the beginning of the list.
6. Overload the operator+() to implement concatenation of two
lists.
This operator is probably the trickiest I have given you to
implement.
This operator should take a const reference to another ListType
as
its parameter for input. This is the list on the right hand side of
the + operation. This function should return a reference to a
new
ListType as its result. It is important that both the input
parameter
and the return type be both reference parameters for this
function.
This function should be a const function, as it does not cause
the
original list to change. Instead you should dynamically allocate
a new
ListType in this function, �ll it with the items from the two
lists being
concatenated, and then return it as the result from this
overloaded
function. You should read our textbook example of overloading
the
operator+() and try and follow that pattern for implementing
this
function.
7. Overload the operator[] indexing operator. This is NOT a
const
member function, your list can change as a result of calling this
func-
tion. This function takes an int value as its input parameter.
This
function should return an int& reference. Again it is very
important
that this overloaded operator return a reference. If this operator
cor-
rectly returns an int&, it can actually be used as a setter to
set/change
3
the values in the list. This operator works to index your
ListType like
an array. You should perform bounds checking in this function.
If the
given input index is not valid (it is bigger than the end of your
list, or
it is < 0), you should display an error message and simply exit.
If you get all of these 7 steps and member functions mostly
working, you
should save/submit your work at that point. However, I am also
o�ering
the opportunity to earn 10 bonus points on this assignment,
which may be
helpful for many of you to make up for some previous program
grades. As
demonstrated in our video for this week, it is usually better if
you want
to create a class template to start from a non-template working
version of
the class. As I showed in the video this week, I usually
templatize each
member function 1 at a time, starting with the class de�nition
and the class
constructors. I will give up to 10 bonus points for a partial or
complete
templatized ListType that supports appending, prepending,
indexing, and
output to streams using the overloaded operators, but for any
type, not just
the int type.
You will again be given 3 starting template �les as usual, an
assg-07.cpp
�le of tests of your code, and a ListType.hpp and ListType.cpp
header and
implementation �le. As before, you should practice incremental
develop-
ment, and uncomment the tests in the assg-07.cpp �le one at a
time, and
implement the functions in the order speci�ed. If you
implement your code
correctly and uncomment all of the tests, you should get the
following correct
output:
--------- Test constructors and getters -------------------------
l1 size: 0 allocSize: 0
l2 size: 0 allocSize: 7
l3 size: 5 allocSize: 5
--------- Test output stream operator ---------------------------
l2 items: []
ListType <id=2>
size = 0
allocSize = 7
items : []
l3 items: [3, 9, 2, 7, 5]
4
ListType <id=3>
size = 5
allocSize = 5
items : [3, 9, 2, 7, 5]
--------- Test append and operator& -----------------------------
<ListType::growListIfNeeded()> LOG: grow list current alloc 0
new alloc 10
append to empty l1:
ListType <id=1>
size = 1
allocSize = 10
items : [1]
<ListType::growListIfNeeded()> LOG: grow list current alloc 5
new alloc 15
append to nonempty l3:
ListType <id=3>
size = 6
allocSize = 15
items : [3, 9, 2, 7, 5, 12]
operator& test l3:
ListType <id=3>
size = 8
allocSize = 15
items : [3, 9, 2, 7, 5, 12, 6, 11]
mixing append and operator& l1:
ListType <id=1>
size = 5
allocSize = 10
items : [1, 4, 3, 7, 0]
--------- Test prepend and operator| ----------------------------
prepend to empty l2:
ListType <id=2>
5
size = 1
allocSize = 7
items : [8]
prepend to nonempty l3:
ListType <id=3>
size = 9
allocSize = 15
items : [8, 3, 9, 2, 7, 5, 12, 6, 11]
operator| test l3:
ListType <id=3>
size = 11
allocSize = 15
items : [4, 13, 8, 3, 9, 2, 7, 5, 12, 6, 11]
<ListType::growListIfNeeded()> LOG: grow list current alloc 7
new alloc 17
mixing prepend and append and operators l2:
ListType <id=2>
size = 8
allocSize = 17
items : [4, 0, 13, 5, 7, 8, 11, 9]
--------- Test concatenation operator ----------------------------
Test basic append, new l4:
ListType <id=4>
size = 19
allocSize = 19
items : [4, 0, 13, 5, 7, 8, 11, 9, 4, 13, 8, 3, 9, 2, 7, 5, 12, 6, 11]
Test basic append, new l5:
ListType <id=6>
size = 24
allocSize = 24
items : [1, 4, 3, 7, 0, 4, 13, 8, 3, 9, 2, 7, 5, 12, 6, 11, 4, 0, 13, 5,
7, 8, 11, 9]
Test concatentate emptyList, new l6:
ListType <id=8>
6
size = 8
allocSize = 8
items : [4, 0, 13, 5, 7, 8, 11, 9]
Test concatentate emptyList, new l7:
ListType <id=9>
size = 5
allocSize = 5
items : [1, 4, 3, 7, 0]
--------- Test operator[] indexing ------------------------------
l1[0] == 1
l1[2] == 3
l1[4] == 0
Iterate over l2:
ListType <id=2>
size = 8
allocSize = 17
items : [4, 0, 13, 5, 7, 8, 11, 9]
l2[0] == 4
l2[1] == 0
l2[2] == 13
l2[3] == 5
l2[4] == 7
l2[5] == 8
l2[6] == 11
l2[7] == 9
ListType setter using operator[] l2[0] == 8
ListType setter using operator[] l2[4] == -7
ListType setter using operator[] l2[7] == 42
--------- main exiting scope, destructors should be invoked -----
ListType: <id=9> out of scope, size: 5 allocSize: 5
ListType: <id=8> out of scope, size: 8 allocSize: 8
ListType: <id=7> out of scope, size: 0 allocSize: 0
7
ListType: <id=6> out of scope, size: 24 allocSize: 24
ListType: <id=4> out of scope, size: 19 allocSize: 19
ListType: <id=3> out of scope, size: 11 allocSize: 15
ListType: <id=2> out of scope, size: 8 allocSize: 17
ListType: <id=1> out of scope, size: 5 allocSize: 10
If you templatize your ListType class, submit this in the second
submis-
sion folder. You should add tests to try out your list with things
other than
ints, like double and string lists.
Assignment Submission
A MyLeoOnline submission folder has been created for this
assignment. You
should attach and upload your completed .cpp source �les to
the submission
folder to complete this assignment. You really do not need to
give me the
assg-07.cpp �le again, as I will have my own �le with
additional tests of
your functions. However, please leave the names of the other
two �les as
QuickSort.hpp and QuickSort.cpp when you submit them.
Requirements and Grading Rubrics
Program Execution, Output and Functional Requirements
1. Your program must compile, run and produce some sort of
output to
be graded. 0 if not satis�ed.
2. (5 pts.) The getter methods getSize() and getAllocSize() are
im-
plemented and working.
3. (10 pts.) tostring() works and only creates a string with the
items
of the list and returns it. opeator<<() works, displays the
additional
information on the output stream, and uses tostring() in its
imple-
mentation.
4. (15 pts.) Got list appending working correctly. The
appendItem()
member function is implemented correctly, and the operator&()
is
overloaded as a member function, and it uses appendItem() to
do the
actual work of appending. Memory is grown if needed by this
function.
5. (15 pts.) Go list prepending working correctly. The
prependItem()
member function is implemented correctly, and the operator|()
is
8
overloaded as a member function, and it uses prependItem() to
do
the actual work of prepending. Items are shifted up which is
necessary
in the array implemented for prepending. Memory is correctly
grown
if needed by this function.
6. (25 pts) operator+() is correctly overloaded. The operator
correctly
supports concatentation of two lists. The operator is de�ned as
a class
const method. The operator correctly dynamically allocates a
new
list and puts the items of the two lists into it, and returns this
newly
allocated object as its result. A reference to the other list is
given as
input, and this function returns a refereunce to a list as the
result.
7. (20 pts) operator[] is correctly overloaded. The operator
returns an
int reference as its result. The operator correctly checks for
bounds
access errors, for indexes to big or less than 0. The operator
correctly
works as a setter method, so that values can be
modi�ed/assigned in
the list.
8. (5 pts.) All output is correct and matches the correct example
output.
9. (5 pts.) Followed class style guidelines, especially those
mentioned
below.
10. (10 bonus pts.) You may templatize your class and submit it
(complete
or partial) for up to 10 bonus points. Your templatized class
must
support all of the overloaded operations (append, prepend,
indexing,
output stream), and work with any class, like string, double, etc.
Program Style
Your programs must conform to the style and formatting
guidelines given
for this class. The following is a list of the guidelines that are
required for
the assignment to be submitted this week.
1. Most importantly, make sure you �gure out how to set your
indentation
settings correctly. All programs must use 2 spaces for all
indentation
levels, and all indentation levels must be correctly indented.
Also all
tabs must be removed from �les, and only 2 spaces used for
indentation.
2. A function header must be present for member functions you
de�ne.
You must give a short description of the function, and document
all of
the input parameters to the function, as well as the return value
and
9
data type of the function if it returns a value for the member
functions,
just like for regular functions. However, setter and getter
methods do
not require function headers.
3. You should have a document header for your class. The class
header
document should give a description of the class. Also you
should doc-
ument all private member variables that the class manages in
the class
document header.
4. Do not include any statements (such as system("pause") or
inputting
a key from the user to continue) that are meant to keep the
terminal
from going away. Do not include any code that is speci�c to a
single
operating system, such as the system("pause") which is
Microsoft
Windows speci�c.
10
/**
* @author Jane Programmer
* @cwid 123 45 678
* @class COSC 2336, Spring 2019
* @ide Visual Studio Community 2017
* @date February 15, 2019
* @assg Assignment 07 Templates and Operator Overloading
*
* @description Assignment 07 part 01, practice with operator
overloading.
* In this first part of assignment, you need to define a
ListType class
* and overload the indicated operators. This version of your
class
* will only support list of int values. You will turn this into a
* class template in part 2 of the assignment.
*/
#include <iostream>
#include <string>
#include <cassert>
#include "ListType.hpp"
using namespace std;
/** main
* The main entry point for this program. Execution of this
program
* will begin with this main function.
*
* @param argc The command line argument count which is the
number of
* command line arguments provided by user when they
started
* the program.
* @param argv The command line arguments, an array of
character
* arrays.
*
* @returns An int value indicating program exit status.
Usually 0
* is returned to indicate normal exit and a non-zero value
* is returned to indicate an error condition.
*/
int main(int argc, char** argv)
{
//-----------------------------------------------------------------------
-
// test constructors and getters
cout << "--------- Test constructors and getters ------------------
-------" << endl;
ListType l1;
//cout << "l1 size: " << l1.getSize()
// << " allocSize: " << l1.getAllocSize() << endl;
//assert(l1.getSize() == 0);
//assert(l1.getAllocSize() == 0);
ListType l2(7); // empty list but with room for 7 items
//cout << "l2 size: " << l2.getSize()
// << " allocSize: " << l2.getAllocSize() << endl;
//assert(l2.getSize() == 0);
//assert(l2.getAllocSize() == 7);
int size = 5;
int items[] = {3, 9, 2, 7, 5};
ListType l3(size, items);
//cout << "l3 size: " << l3.getSize()
// << " allocSize: " << l3.getAllocSize() << endl;
//assert(l3.getSize() == 5);
//assert(l3.getAllocSize() == 5);
cout << endl << endl;
//-----------------------------------------------------------------------
-
// test output stream operator implementation
cout << "--------- Test output stream operator --------------------
-------" << endl;
//cout << "l2 items: " << l2.tostring() << endl;
//assert(l2.tostring() == "[]");
//cout << l2 << endl << endl;
//cout << "l3 items: " << l3.tostring() << endl;
//assert(l3.tostring() == "[3, 9, 2, 7, 5]");
//cout << l3 << endl << endl;
cout << endl << endl;
//-----------------------------------------------------------------------
-
// test appending and operator& overloading
cout << "--------- Test append and operator& --------------------
---------" << endl;
// append to empty list
//l1.appendItem(1);
//cout << "append to empty l1: " << endl << l1 << endl;
//assert(l1.tostring() == "[1]" );
//assert(l1.getSize() == 1);
//assert(l1.getAllocSize() == 10);
// append to non empty list
//l3.appendItem(12);
//cout << "append to nonempty l3: " << endl << l3 << endl;
//assert(l3.tostring() == "[3, 9, 2, 7, 5, 12]" );
//assert(l3.getSize() == 6);
//assert(l3.getAllocSize() == 15);
// append 2 items using operator& and test
//l3 & 6;
//l3 & 11;
//cout << "operator& test l3: " << endl << l3 << endl;
//assert(l3.tostring() == "[3, 9, 2, 7, 5, 12, 6, 11]" );
//assert(l3.getSize() == 8);
//assert(l3.getAllocSize() == 15);
// some more, mix up append function and operator
//l1.appendItem(4);
//l1 & 3;
//l1 & 7;
//l1.appendItem(0);
//cout << "mixing append and operator& l1: " << endl << l1
<< endl;
//assert(l1.tostring() == "[1, 4, 3, 7, 0]");
//assert(l1.getSize() == 5);
//assert(l1.getAllocSize() == 10);
cout << endl << endl;
//-----------------------------------------------------------------------
-
// test prepending operator| overloading
cout << "--------- Test prepend and operator| ---------------------
-------" << endl;
// prepend to empty list
//l2.prependItem(8);
//cout << "prepend to empty l2: " << endl << l2 << endl;
//assert(l2.tostring() == "[8]" );
//assert(l2.getSize() == 1);
//assert(l2.getAllocSize() == 7);
// prepend to nonempty list
//l3.prependItem(8);
//cout << "prepend to nonempty l3: " << endl << l3 << endl;
//assert(l3.tostring() == "[8, 3, 9, 2, 7, 5, 12, 6, 11]" );
//assert(l3.getSize() == 9);
//assert(l3.getAllocSize() == 15);
// operator| test
//l3 | 13;
//l3 | 4;
//cout << "operator| test l3: " << endl << l3 << endl;
//assert(l3.tostring() == "[4, 13, 8, 3, 9, 2, 7, 5, 12, 6, 11]");
//assert(l3.getSize() == 11);
//assert(l3.getAllocSize() == 15);
// some more, mix up prepend function and operator
//l2.prependItem(7);
//l2 & 11;
//l2 | 5;
//l2.appendItem(9);
//l2 | 13;
//l2 | 0;
//l2 | 4;
//cout << "mixing prepend and append and operators l2: " <<
endl << l2 << endl;
//assert(l2.tostring() == "[4, 0, 13, 5, 7, 8, 11, 9]");
//assert(l2.getSize() == 8);
//assert(l2.getAllocSize() == 17);
cout << endl << endl;
//-----------------------------------------------------------------------
-
// test concatenation
cout << "--------- Test concatenation operator -------------------
---------" << endl;
//ListType l4 = l2 + l3;
//cout << "Test basic append, new l4: " << endl << l4 << endl;
//assert(l4.tostring() == "[4, 0, 13, 5, 7, 8, 11, 9, 4, 13, 8, 3, 9,
2, 7, 5, 12, 6, 11]");
//assert(l4.getSize() == 19);
//assert(l4.getAllocSize() == 19);
//ListType l5 = l1 + l3 + l2;
//cout << "Test basic append, new l5: " << endl << l5 << endl;
//assert(l5.tostring() == "[1, 4, 3, 7, 0, 4, 13, 8, 3, 9, 2, 7, 5,
12, 6, 11, 4, 0, 13, 5, 7, 8, 11, 9]");
//assert(l5.getSize() == 24);
//assert(l5.getAllocSize() == 24);
//ListType emptyList;
//ListType l6 = l2 + emptyList;
//cout << "Test concatentate emptyList, new l6: " << endl <<
l6 << endl;
//assert(l6.tostring() == l2.tostring());
//assert(l6.getSize() == 8);
//assert(l6.getAllocSize() == 8);
//ListType l7 = emptyList + l1;
//cout << "Test concatentate emptyList, new l7: " << endl <<
l7 << endl;
//assert(l7.tostring() == l1.tostring());
//assert(l7.getSize() == 5);
//assert(l7.getAllocSize() == 5);
cout << endl << endl;
//-----------------------------------------------------------------------
-
// test operator[] indexing and setter
cout << "--------- Test operator[] indexing -----------------------
-------" << endl;
//cout << "l1[0] == " << l1[0] << endl;
//assert(l1[0] == 1);
//cout << "l1[2] == " << l1[2] << endl;
//assert(l1[2] == 3);
//cout << "l1[4] == " << l1[4] << endl;
//assert(l1[4] == 0);
//cout << "Iterate over l2:" << endl << l2 << endl;
//for (int index = 0; index < l2.getSize(); index++)
//{
// cout << " l2[" << index << "] == " << l2[index] << endl;
//}
//cout << endl;
//l2[0] = 8;
//cout << "ListType setter using operator[] l2[0] == " << l2[0]
<< endl;
//assert(l2[0] == 8);
//l2[4] = -7;
//cout << "ListType setter using operator[] l2[4] == " << l2[4]
<< endl;
//assert(l2[4] == -7);
//l2[7] = 42;
//cout << "ListType setter using operator[] l2[7] == " << l2[7]
<< endl;
//assert(l2[7] == 42);
// test bounds checking on operator[]
// you should uncomment these to test, but you shouldn't leave
them uncommented
// should cause exit and error message
//cout << l2[-5];
// should cause exit and error message
//cout << l2[8];
cout << endl << endl;
//-----------------------------------------------------------------------
-
// test out of scope, destructors should be called
cout << "--------- main exiting scope, destructors should be
invoked -----" << endl;
// return 0 to indicate successful completion
return 0;
}
/**
* @author Jane Programmer
* @cwid 123 45 678
* @class COSC 2336, Spring 2019
* @ide Visual Studio Community 2017
* @date February 15, 2019
* @assg Assignment 07 Operator Overloading
*
* @description Assignment 07 part 01, practice with operator
overloading.
* In this first part of assignment, you need to define a
ListType class
* and overload the indicated operators. This version of your
class
* will only support list of int values. You will turn this into a
* class template in part 2 of the assignment.
*/
#include "ListType.hpp"
// static member variables have to be initialized like this
int ListType::nextListId = 1;
/** default constructor
* Initialize as an empty list. Initially we have no memory
* allocated, and the size (and allocation size) are 0.
*/
ListType::ListType()
{
id = nextListId++;
size = allocSize = 0;
item = NULL;
}
/** constructor (empty)
* Initialize as an empty list with indicated iniaial
* size of memory allocated.
*
* @param allocSize The initialze size for the empty list.
*/
ListType::ListType(int allocSize)
{
id = nextListId++;
size = 0;
this->allocSize = allocSize;
item = new int[this->allocSize];
}
/** constructor (array)
* Initialize a list using an array of items for the initial values
* in the list.
*
* @param size The number of items in the array given for
initialization.
* @param items An array (pointer to base address) of items to
initialize
* this list with.
*/
ListType::ListType(int size, int* initItem)
{
id = nextListId++;
this->size = size;
this->allocSize = size;
item = new int[this->size];
// copy the items into this list
for (int index = 0; index < this->size; index++)
{
item[index] = initItem[index];
}
}
/** destructor
* The class destructor. Be good stewards of memory and make
* sure that we free up memory allocated to hold our list items
* by this object when it goes out of scope. We display some
* information for debugging/tracking ListType destruction.
*/
ListType::~ListType()
{
cout << "ListType: <id=" << id << "> out of scope, size: "
<< size
<< " allocSize: " << allocSize << endl;
// be a good memory manager, free up memory we have
allocated
if (item != NULL)
{
delete [] item;
}
}
/** overload operator=
* Overload the operator= assignment operator. Whenever one
list
* variable is assigned to another this operator is invoked.
*
* @param rhs The list on the right hand side of the assignment,
the
* contents of which is to be (deep) copied to this list contents.
*
* @returns ListType Returns a reference to this list, after
contents
* have been copied/assigned.
*/
const ListType& ListType::operator=(const ListType& rhs)
{
// only assign if not doing a self-assignment
if (this != &rhs)
{
// copy the values from rightList into this list
int newAllocSize = rhs.size;
// if not enough space, grow our list
if (this->allocSize < newAllocSize)
{
int* newItem = new int[newAllocSize];
delete [] item;
item = newItem;
this->allocSize = newAllocSize;
}
// copy the items from righ hand side into this list
for (int index = 0; index < rhs.size; index++)
{
this->item[index] = rhs.item[index];
}
this->size = rhs.size;
}
// return the object assigned
return *this;
}
/**
* @author Jane Programmer
* @cwid 123 45 678
* @class COSC 2336, Spring 2019
* @ide Visual Studio Community 2017
* @date February 15, 2019
* @assg Assignment 07 Operator Overloading
*
* @description Assignment 07 part 01, practice with operator
overloading.
* In this first part of assignment, you need to define a
ListType class
* and overload the indicated operators. This version of your
class
* will only support list of int values. You will turn this into a
* class template in part 2 of the assignment.
*/
#include <iostream>
#include <sstream>
using namespace std;
#ifndef _LISTTYPE_H_
#define _LISTTYPE_H_
/** ListType abstract data type
* This list type is "templatized" to support creating concrete
lists of
* any type of object. This list supports dynamic shrinking and
growing
* of its size as items are appended and removed from the list.
* In addition, several operators are overloaded for convenience
of
* inserting, accessing and outputting the list to a stream.
*
* @value id A unique id, each list is assigned its own unique id
* upon creation.
* @value size The current size (an int) or number of items
currently
* contained in the list.
* @value allocSize The actual amount of memory we currently
* have allocated.
* @value item A (pointer to an) array of items of our templated
* <Type> we are holding in our list.
*/
class ListType
{
private:
// initial allocSize, unless overridden in construction
const int ALLOCATION_INCREMENT = 10;
static int nextListId; // class variable, assign unique listid
int id;
int size;
int allocSize;
int* item;
public:
ListType(); // default constructor
ListType(int allocSize); // empty constructor
ListType(int size, int* items); // construct from array
~ListType(); // class destructor
// getters
// member functions
// overloaded operators
const ListType& operator=(const ListType& rightList); // I
also gave you the copy operator
};
// need to include the template implementations here, if/when
you templatize
//#include "ListType.cpp"
#endif // _LISTTYPE_H_

More Related Content

DOCX
#ifndef MYLIST_H_ #define MYLIST_H_#includeiostream #include.docx
PDF
C++ projectMachine Problem 7 - HashingWrite a program to do the .pdf
PDF
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
PDF
helpInstructionsAdd the function max as an abstract function to .pdf
PDF
In C++Write a recursive function to determine whether or not a Lin.pdf
DOCX
COS30008 Semester 1, 2016 Dr. Markus Lumpe 1 Swinbu.docx
PDF
This assignment and the next (#5) involve design and development of a.pdf
PDF
(Unordered Sets) As explained in this chapter, a set is a collection.pdf
#ifndef MYLIST_H_ #define MYLIST_H_#includeiostream #include.docx
C++ projectMachine Problem 7 - HashingWrite a program to do the .pdf
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
helpInstructionsAdd the function max as an abstract function to .pdf
In C++Write a recursive function to determine whether or not a Lin.pdf
COS30008 Semester 1, 2016 Dr. Markus Lumpe 1 Swinbu.docx
This assignment and the next (#5) involve design and development of a.pdf
(Unordered Sets) As explained in this chapter, a set is a collection.pdf

Similar to Assg 07 Templates and Operator OverloadingCOSC 2336 Sprin.docx (20)

PPTX
Programming Assignment Help
DOCX
Program 8 C++newproblems.txt12333142013KristinBrewer1032823.docx
PDF
Consider a double-linked linked list implementation with the followin.pdf
DOCX
Linked lists
PPTX
CPP Assignment Help
PDF
Using c++Im also using a the ide editor called CodeLiteThe hea.pdf
PDF
Please code in C++ and do only the �TO DO�s and all of them. There a.pdf
DOCX
Write a program to find the number of comparisons using the binary se.docx
PDF
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
PDF
Implement the ListArray ADT-Implement the following operations.pdf
PDF
Complete a C++ class implementation for a linked-list of sorted (asc.pdf
PDF
1- The design of a singly-linked list below is a picture of the functi (1).pdf
PDF
In C++Add the function min as an abstract function to the classar.pdf
PDF
All code should be in C++Using the UnsortedList class (UnsortedLis.pdf
PDF
Dividing a linked list into two sublists of almost equal sizesa. A.pdf
PDF
Using the C++ programming language1. Implement the UnsortedList cl.pdf
PDF
include ltfunctionalgt include ltiteratorgt inclu.pdf
PDF
Using C++I keep getting messagehead does not name a type.pdf
PDF
implement the ListLinked ADT (the declaration is given in ListLinked.pdf
PDF
Please complete ALL of the �TO DO�s in this code. I am really strugg.pdf
Programming Assignment Help
Program 8 C++newproblems.txt12333142013KristinBrewer1032823.docx
Consider a double-linked linked list implementation with the followin.pdf
Linked lists
CPP Assignment Help
Using c++Im also using a the ide editor called CodeLiteThe hea.pdf
Please code in C++ and do only the �TO DO�s and all of them. There a.pdf
Write a program to find the number of comparisons using the binary se.docx
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
Implement the ListArray ADT-Implement the following operations.pdf
Complete a C++ class implementation for a linked-list of sorted (asc.pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdf
In C++Add the function min as an abstract function to the classar.pdf
All code should be in C++Using the UnsortedList class (UnsortedLis.pdf
Dividing a linked list into two sublists of almost equal sizesa. A.pdf
Using the C++ programming language1. Implement the UnsortedList cl.pdf
include ltfunctionalgt include ltiteratorgt inclu.pdf
Using C++I keep getting messagehead does not name a type.pdf
implement the ListLinked ADT (the declaration is given in ListLinked.pdf
Please complete ALL of the �TO DO�s in this code. I am really strugg.pdf
Ad

More from festockton (20)

DOCX
Learning ResourcesRequired ReadingsToseland, R. W., & Ri.docx
DOCX
LeamosEscribamos Completa el párrafo con las formas correctas de lo.docx
DOCX
Leadership via vision is necessary for success. Discuss in detail .docx
DOCX
Learning about Language by Observing and ListeningThe real.docx
DOCX
Learning Accomplishment Profile-Diagnostic Spanish Language Edit.docx
DOCX
Learning about Language by Observing and ListeningThe real voy.docx
DOCX
LEARNING OUTCOMES1. Have knowledge and understanding of the pri.docx
DOCX
Leadership Style What do people do when they are leadingAssignme.docx
DOCX
Leadership Throughout HistoryHistory is filled with tales of leade.docx
DOCX
Lean Inventory Management1. Why do you think lean inventory manage.docx
DOCX
Leadership varies widely by culture and personality. An internationa.docx
DOCX
Leadership is the ability to influence people toward the attainment .docx
DOCX
Lawday. Court of Brightwaltham holden on Monday next after Ascension.docx
DOCX
law43665_fm_i-xx i 010719 1032 AMStakeholders, Eth.docx
DOCX
Leaders face many hurdles when leading in multiple countries. There .docx
DOCX
Last year Angelina Jolie had a double mastectomy because of re.docx
DOCX
Leaders face many hurdles when leading in multiple countries. Ther.docx
DOCX
Leaders today must be able to create a compelling vision for the org.docx
DOCX
Law enforcement professionals and investigators use digital fore.docx
DOCX
LAW and Economics 4 questionsLaw And EconomicsTextsCoote.docx
Learning ResourcesRequired ReadingsToseland, R. W., & Ri.docx
LeamosEscribamos Completa el párrafo con las formas correctas de lo.docx
Leadership via vision is necessary for success. Discuss in detail .docx
Learning about Language by Observing and ListeningThe real.docx
Learning Accomplishment Profile-Diagnostic Spanish Language Edit.docx
Learning about Language by Observing and ListeningThe real voy.docx
LEARNING OUTCOMES1. Have knowledge and understanding of the pri.docx
Leadership Style What do people do when they are leadingAssignme.docx
Leadership Throughout HistoryHistory is filled with tales of leade.docx
Lean Inventory Management1. Why do you think lean inventory manage.docx
Leadership varies widely by culture and personality. An internationa.docx
Leadership is the ability to influence people toward the attainment .docx
Lawday. Court of Brightwaltham holden on Monday next after Ascension.docx
law43665_fm_i-xx i 010719 1032 AMStakeholders, Eth.docx
Leaders face many hurdles when leading in multiple countries. There .docx
Last year Angelina Jolie had a double mastectomy because of re.docx
Leaders face many hurdles when leading in multiple countries. Ther.docx
Leaders today must be able to create a compelling vision for the org.docx
Law enforcement professionals and investigators use digital fore.docx
LAW and Economics 4 questionsLaw And EconomicsTextsCoote.docx
Ad

Recently uploaded (20)

PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Institutional Correction lecture only . . .
PPTX
Presentation on HIE in infants and its manifestations
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Classroom Observation Tools for Teachers
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
A systematic review of self-coping strategies used by university students to ...
PDF
01-Introduction-to-Information-Management.pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Computing-Curriculum for Schools in Ghana
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Supply Chain Operations Speaking Notes -ICLT Program
human mycosis Human fungal infections are called human mycosis..pptx
Institutional Correction lecture only . . .
Presentation on HIE in infants and its manifestations
VCE English Exam - Section C Student Revision Booklet
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Classroom Observation Tools for Teachers
STATICS OF THE RIGID BODIES Hibbelers.pdf
202450812 BayCHI UCSC-SV 20250812 v17.pptx
2.FourierTransform-ShortQuestionswithAnswers.pdf
A systematic review of self-coping strategies used by university students to ...
01-Introduction-to-Information-Management.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Anesthesia in Laparoscopic Surgery in India
Computing-Curriculum for Schools in Ghana
Module 4: Burden of Disease Tutorial Slides S2 2025

Assg 07 Templates and Operator OverloadingCOSC 2336 Sprin.docx

  • 1. Assg 07: Templates and Operator Overloading COSC 2336 Spring 2019 Dates: Due: Thursday March 07, by Midnight (note the di�erent due date) Objectives � Practice creating a more realistic abstract data type ADT � Using operator overloading to do output, insertion and access into a list. � Use templates so our ADT can hold objects of any type Description In this assignment you will be practicing operator overloading. I will also, for extra credit, give an additional task to convert your class into a class template, so that it will work as a container for any type. In this assignment you will be expanding on / creating a new version of the ListType data type we have seen examples of before in class. Your task is to create a ListType that holds a list of integers. You will be
  • 2. asked to create several member functions, and then to create several overloaded operators for your list of integers. Your basic task is to user operator overloading to support appending and prepending to a list, outputting the list as a string and to an output stream, accessing the list (using the indexing operator[]), and concatenating lists together (using operator+). I have given you a starting template for your ListType that already contains 3 versions of the class constructor. I have also already provided you the operator= implementation, to provide the copy operator for your class. You should �rst get your class to work as a simple ListType that holds a list of integers. If you get your class working for integers and submit it, you 1 can then turn your class into a template class, so that your list can work on objects of any type. I will give up to 10 bonus points for implementations of working class templates, if you �rst mostly have your basic ListType working for simple integers. As usual I have also given a �le with a main function and a lot of commented out tests. You should implement the class member
  • 3. functions in the order speci�ed next, commenting out each test one at a time, to incrementally develop and test your ListType class implementation. For this assignment you need to perform the following tasks. 1. As mentioned in the starting template I have given you a starting class de�nition, some class constructors and the destructor, and the copy operator=. You �rst need to write two simple getter methods in order to access the size and allocSize class member values. These should be called getSize() and getAllocSize() respectively. These functions should be class const functions (you guarantee that calling them will not cause the class to be modi�ed. These functions take no parameters as input. They both return an int value, because the size and allocSize member parameters are both integer values. 2. Write a function called tostring(). This function will be a const class function (the class is not modi�ed when it is called). This function takes no parameters as input, and it returns a string. We use this function in our testing, so you need to get it correct, but you have implemented versions of this type of function in previous assignments. The function should only create a string of the items currently in the
  • 4. list. So it will return a string like "[3, 5, 4, 2]" if those are the 4 items currently in the list. See the test code for speci�cs. 3. Overload the operator<<() to provide the ability for the ListType class to be output to a stream. This will be a friend function, and again it will be pretty similar to several examples we have seen of overloading the output stream operator. You should use the tostring() method in this function, but it outputs additional information, such as the id, size and allocSize of the list to the output stream. 4. Create a function named appendItem(). This function takes an int value as its only parameter, and it does not return a value. The indi- cated integer value should be appended to the end of your list when this function is called. You need to correctly handle causing the size of your memory allocation to grow if needed in this function, if your list is currently using all of the allocated memory. Once this is working, 2 overload the operator&() operator. We will de�ne the & operator to mean list appending. For example, if you do list & 5 it will
  • 5. cause 5 to be appended to the end of the list (assuming list is a variable of List- Type). This function will simply call appendItem() to do the work, the only di�culty is getting the syntax correct to declare you are over- loading the operator. This is not a friend function, like operator<<(). Read our textbook about binary operators to see examples of how to overload a binary operator like this as a member function of a class. 5. Create a function name prependItem(). This works the same as the append, but it prepends the indicated integer parameter to the front of the list instead of to the end. However, you still need to check and grow your allocated memory before prepending if your list is currently full. Also prepend is a bit more complicated, because since we are implementing an array based list, you need to shift all of the current items 1 index up in your items before you can prepend to the beginning of the list. We will also overload the operator|() for our class to represent prepending an item. Thus if you do list | 5 this will cause 5 to be prepended to the beginning of the list. 6. Overload the operator+() to implement concatenation of two lists. This operator is probably the trickiest I have given you to
  • 6. implement. This operator should take a const reference to another ListType as its parameter for input. This is the list on the right hand side of the + operation. This function should return a reference to a new ListType as its result. It is important that both the input parameter and the return type be both reference parameters for this function. This function should be a const function, as it does not cause the original list to change. Instead you should dynamically allocate a new ListType in this function, �ll it with the items from the two lists being concatenated, and then return it as the result from this overloaded function. You should read our textbook example of overloading the operator+() and try and follow that pattern for implementing this function. 7. Overload the operator[] indexing operator. This is NOT a const member function, your list can change as a result of calling this func- tion. This function takes an int value as its input parameter. This function should return an int& reference. Again it is very important that this overloaded operator return a reference. If this operator cor- rectly returns an int&, it can actually be used as a setter to set/change
  • 7. 3 the values in the list. This operator works to index your ListType like an array. You should perform bounds checking in this function. If the given input index is not valid (it is bigger than the end of your list, or it is < 0), you should display an error message and simply exit. If you get all of these 7 steps and member functions mostly working, you should save/submit your work at that point. However, I am also o�ering the opportunity to earn 10 bonus points on this assignment, which may be helpful for many of you to make up for some previous program grades. As demonstrated in our video for this week, it is usually better if you want to create a class template to start from a non-template working version of the class. As I showed in the video this week, I usually templatize each member function 1 at a time, starting with the class de�nition and the class constructors. I will give up to 10 bonus points for a partial or complete templatized ListType that supports appending, prepending, indexing, and output to streams using the overloaded operators, but for any type, not just the int type.
  • 8. You will again be given 3 starting template �les as usual, an assg-07.cpp �le of tests of your code, and a ListType.hpp and ListType.cpp header and implementation �le. As before, you should practice incremental develop- ment, and uncomment the tests in the assg-07.cpp �le one at a time, and implement the functions in the order speci�ed. If you implement your code correctly and uncomment all of the tests, you should get the following correct output: --------- Test constructors and getters ------------------------- l1 size: 0 allocSize: 0 l2 size: 0 allocSize: 7 l3 size: 5 allocSize: 5 --------- Test output stream operator --------------------------- l2 items: [] ListType <id=2> size = 0 allocSize = 7 items : [] l3 items: [3, 9, 2, 7, 5]
  • 9. 4 ListType <id=3> size = 5 allocSize = 5 items : [3, 9, 2, 7, 5] --------- Test append and operator& ----------------------------- <ListType::growListIfNeeded()> LOG: grow list current alloc 0 new alloc 10 append to empty l1: ListType <id=1> size = 1 allocSize = 10 items : [1] <ListType::growListIfNeeded()> LOG: grow list current alloc 5 new alloc 15 append to nonempty l3: ListType <id=3> size = 6
  • 10. allocSize = 15 items : [3, 9, 2, 7, 5, 12] operator& test l3: ListType <id=3> size = 8 allocSize = 15 items : [3, 9, 2, 7, 5, 12, 6, 11] mixing append and operator& l1: ListType <id=1> size = 5 allocSize = 10 items : [1, 4, 3, 7, 0] --------- Test prepend and operator| ---------------------------- prepend to empty l2: ListType <id=2> 5 size = 1
  • 11. allocSize = 7 items : [8] prepend to nonempty l3: ListType <id=3> size = 9 allocSize = 15 items : [8, 3, 9, 2, 7, 5, 12, 6, 11] operator| test l3: ListType <id=3> size = 11 allocSize = 15 items : [4, 13, 8, 3, 9, 2, 7, 5, 12, 6, 11] <ListType::growListIfNeeded()> LOG: grow list current alloc 7 new alloc 17 mixing prepend and append and operators l2: ListType <id=2> size = 8 allocSize = 17
  • 12. items : [4, 0, 13, 5, 7, 8, 11, 9] --------- Test concatenation operator ---------------------------- Test basic append, new l4: ListType <id=4> size = 19 allocSize = 19 items : [4, 0, 13, 5, 7, 8, 11, 9, 4, 13, 8, 3, 9, 2, 7, 5, 12, 6, 11] Test basic append, new l5: ListType <id=6> size = 24 allocSize = 24 items : [1, 4, 3, 7, 0, 4, 13, 8, 3, 9, 2, 7, 5, 12, 6, 11, 4, 0, 13, 5, 7, 8, 11, 9] Test concatentate emptyList, new l6: ListType <id=8> 6 size = 8 allocSize = 8
  • 13. items : [4, 0, 13, 5, 7, 8, 11, 9] Test concatentate emptyList, new l7: ListType <id=9> size = 5 allocSize = 5 items : [1, 4, 3, 7, 0] --------- Test operator[] indexing ------------------------------ l1[0] == 1 l1[2] == 3 l1[4] == 0 Iterate over l2: ListType <id=2> size = 8 allocSize = 17 items : [4, 0, 13, 5, 7, 8, 11, 9] l2[0] == 4 l2[1] == 0 l2[2] == 13
  • 14. l2[3] == 5 l2[4] == 7 l2[5] == 8 l2[6] == 11 l2[7] == 9 ListType setter using operator[] l2[0] == 8 ListType setter using operator[] l2[4] == -7 ListType setter using operator[] l2[7] == 42 --------- main exiting scope, destructors should be invoked ----- ListType: <id=9> out of scope, size: 5 allocSize: 5 ListType: <id=8> out of scope, size: 8 allocSize: 8 ListType: <id=7> out of scope, size: 0 allocSize: 0 7 ListType: <id=6> out of scope, size: 24 allocSize: 24 ListType: <id=4> out of scope, size: 19 allocSize: 19 ListType: <id=3> out of scope, size: 11 allocSize: 15 ListType: <id=2> out of scope, size: 8 allocSize: 17
  • 15. ListType: <id=1> out of scope, size: 5 allocSize: 10 If you templatize your ListType class, submit this in the second submis- sion folder. You should add tests to try out your list with things other than ints, like double and string lists. Assignment Submission A MyLeoOnline submission folder has been created for this assignment. You should attach and upload your completed .cpp source �les to the submission folder to complete this assignment. You really do not need to give me the assg-07.cpp �le again, as I will have my own �le with additional tests of your functions. However, please leave the names of the other two �les as QuickSort.hpp and QuickSort.cpp when you submit them. Requirements and Grading Rubrics Program Execution, Output and Functional Requirements 1. Your program must compile, run and produce some sort of output to be graded. 0 if not satis�ed. 2. (5 pts.) The getter methods getSize() and getAllocSize() are im- plemented and working. 3. (10 pts.) tostring() works and only creates a string with the
  • 16. items of the list and returns it. opeator<<() works, displays the additional information on the output stream, and uses tostring() in its imple- mentation. 4. (15 pts.) Got list appending working correctly. The appendItem() member function is implemented correctly, and the operator&() is overloaded as a member function, and it uses appendItem() to do the actual work of appending. Memory is grown if needed by this function. 5. (15 pts.) Go list prepending working correctly. The prependItem() member function is implemented correctly, and the operator|() is 8 overloaded as a member function, and it uses prependItem() to do the actual work of prepending. Items are shifted up which is necessary in the array implemented for prepending. Memory is correctly grown if needed by this function. 6. (25 pts) operator+() is correctly overloaded. The operator correctly supports concatentation of two lists. The operator is de�ned as
  • 17. a class const method. The operator correctly dynamically allocates a new list and puts the items of the two lists into it, and returns this newly allocated object as its result. A reference to the other list is given as input, and this function returns a refereunce to a list as the result. 7. (20 pts) operator[] is correctly overloaded. The operator returns an int reference as its result. The operator correctly checks for bounds access errors, for indexes to big or less than 0. The operator correctly works as a setter method, so that values can be modi�ed/assigned in the list. 8. (5 pts.) All output is correct and matches the correct example output. 9. (5 pts.) Followed class style guidelines, especially those mentioned below. 10. (10 bonus pts.) You may templatize your class and submit it (complete or partial) for up to 10 bonus points. Your templatized class must support all of the overloaded operations (append, prepend, indexing, output stream), and work with any class, like string, double, etc. Program Style
  • 18. Your programs must conform to the style and formatting guidelines given for this class. The following is a list of the guidelines that are required for the assignment to be submitted this week. 1. Most importantly, make sure you �gure out how to set your indentation settings correctly. All programs must use 2 spaces for all indentation levels, and all indentation levels must be correctly indented. Also all tabs must be removed from �les, and only 2 spaces used for indentation. 2. A function header must be present for member functions you de�ne. You must give a short description of the function, and document all of the input parameters to the function, as well as the return value and 9 data type of the function if it returns a value for the member functions, just like for regular functions. However, setter and getter methods do not require function headers. 3. You should have a document header for your class. The class header document should give a description of the class. Also you
  • 19. should doc- ument all private member variables that the class manages in the class document header. 4. Do not include any statements (such as system("pause") or inputting a key from the user to continue) that are meant to keep the terminal from going away. Do not include any code that is speci�c to a single operating system, such as the system("pause") which is Microsoft Windows speci�c. 10 /** * @author Jane Programmer * @cwid 123 45 678 * @class COSC 2336, Spring 2019 * @ide Visual Studio Community 2017 * @date February 15, 2019 * @assg Assignment 07 Templates and Operator Overloading * * @description Assignment 07 part 01, practice with operator overloading. * In this first part of assignment, you need to define a ListType class * and overload the indicated operators. This version of your class * will only support list of int values. You will turn this into a * class template in part 2 of the assignment. */ #include <iostream>
  • 20. #include <string> #include <cassert> #include "ListType.hpp" using namespace std; /** main * The main entry point for this program. Execution of this program * will begin with this main function. * * @param argc The command line argument count which is the number of * command line arguments provided by user when they started * the program. * @param argv The command line arguments, an array of character * arrays. * * @returns An int value indicating program exit status. Usually 0 * is returned to indicate normal exit and a non-zero value * is returned to indicate an error condition. */ int main(int argc, char** argv) { //----------------------------------------------------------------------- - // test constructors and getters cout << "--------- Test constructors and getters ------------------ -------" << endl; ListType l1; //cout << "l1 size: " << l1.getSize() // << " allocSize: " << l1.getAllocSize() << endl;
  • 21. //assert(l1.getSize() == 0); //assert(l1.getAllocSize() == 0); ListType l2(7); // empty list but with room for 7 items //cout << "l2 size: " << l2.getSize() // << " allocSize: " << l2.getAllocSize() << endl; //assert(l2.getSize() == 0); //assert(l2.getAllocSize() == 7); int size = 5; int items[] = {3, 9, 2, 7, 5}; ListType l3(size, items); //cout << "l3 size: " << l3.getSize() // << " allocSize: " << l3.getAllocSize() << endl; //assert(l3.getSize() == 5); //assert(l3.getAllocSize() == 5); cout << endl << endl; //----------------------------------------------------------------------- - // test output stream operator implementation cout << "--------- Test output stream operator -------------------- -------" << endl; //cout << "l2 items: " << l2.tostring() << endl; //assert(l2.tostring() == "[]"); //cout << l2 << endl << endl; //cout << "l3 items: " << l3.tostring() << endl; //assert(l3.tostring() == "[3, 9, 2, 7, 5]"); //cout << l3 << endl << endl; cout << endl << endl;
  • 22. //----------------------------------------------------------------------- - // test appending and operator& overloading cout << "--------- Test append and operator& -------------------- ---------" << endl; // append to empty list //l1.appendItem(1); //cout << "append to empty l1: " << endl << l1 << endl; //assert(l1.tostring() == "[1]" ); //assert(l1.getSize() == 1); //assert(l1.getAllocSize() == 10); // append to non empty list //l3.appendItem(12); //cout << "append to nonempty l3: " << endl << l3 << endl; //assert(l3.tostring() == "[3, 9, 2, 7, 5, 12]" ); //assert(l3.getSize() == 6); //assert(l3.getAllocSize() == 15); // append 2 items using operator& and test //l3 & 6; //l3 & 11; //cout << "operator& test l3: " << endl << l3 << endl; //assert(l3.tostring() == "[3, 9, 2, 7, 5, 12, 6, 11]" ); //assert(l3.getSize() == 8); //assert(l3.getAllocSize() == 15); // some more, mix up append function and operator //l1.appendItem(4); //l1 & 3; //l1 & 7; //l1.appendItem(0); //cout << "mixing append and operator& l1: " << endl << l1 << endl;
  • 23. //assert(l1.tostring() == "[1, 4, 3, 7, 0]"); //assert(l1.getSize() == 5); //assert(l1.getAllocSize() == 10); cout << endl << endl; //----------------------------------------------------------------------- - // test prepending operator| overloading cout << "--------- Test prepend and operator| --------------------- -------" << endl; // prepend to empty list //l2.prependItem(8); //cout << "prepend to empty l2: " << endl << l2 << endl; //assert(l2.tostring() == "[8]" ); //assert(l2.getSize() == 1); //assert(l2.getAllocSize() == 7); // prepend to nonempty list //l3.prependItem(8); //cout << "prepend to nonempty l3: " << endl << l3 << endl; //assert(l3.tostring() == "[8, 3, 9, 2, 7, 5, 12, 6, 11]" ); //assert(l3.getSize() == 9); //assert(l3.getAllocSize() == 15); // operator| test //l3 | 13; //l3 | 4; //cout << "operator| test l3: " << endl << l3 << endl; //assert(l3.tostring() == "[4, 13, 8, 3, 9, 2, 7, 5, 12, 6, 11]"); //assert(l3.getSize() == 11); //assert(l3.getAllocSize() == 15); // some more, mix up prepend function and operator
  • 24. //l2.prependItem(7); //l2 & 11; //l2 | 5; //l2.appendItem(9); //l2 | 13; //l2 | 0; //l2 | 4; //cout << "mixing prepend and append and operators l2: " << endl << l2 << endl; //assert(l2.tostring() == "[4, 0, 13, 5, 7, 8, 11, 9]"); //assert(l2.getSize() == 8); //assert(l2.getAllocSize() == 17); cout << endl << endl; //----------------------------------------------------------------------- - // test concatenation cout << "--------- Test concatenation operator ------------------- ---------" << endl; //ListType l4 = l2 + l3; //cout << "Test basic append, new l4: " << endl << l4 << endl; //assert(l4.tostring() == "[4, 0, 13, 5, 7, 8, 11, 9, 4, 13, 8, 3, 9, 2, 7, 5, 12, 6, 11]"); //assert(l4.getSize() == 19); //assert(l4.getAllocSize() == 19); //ListType l5 = l1 + l3 + l2; //cout << "Test basic append, new l5: " << endl << l5 << endl; //assert(l5.tostring() == "[1, 4, 3, 7, 0, 4, 13, 8, 3, 9, 2, 7, 5, 12, 6, 11, 4, 0, 13, 5, 7, 8, 11, 9]"); //assert(l5.getSize() == 24); //assert(l5.getAllocSize() == 24);
  • 25. //ListType emptyList; //ListType l6 = l2 + emptyList; //cout << "Test concatentate emptyList, new l6: " << endl << l6 << endl; //assert(l6.tostring() == l2.tostring()); //assert(l6.getSize() == 8); //assert(l6.getAllocSize() == 8); //ListType l7 = emptyList + l1; //cout << "Test concatentate emptyList, new l7: " << endl << l7 << endl; //assert(l7.tostring() == l1.tostring()); //assert(l7.getSize() == 5); //assert(l7.getAllocSize() == 5); cout << endl << endl; //----------------------------------------------------------------------- - // test operator[] indexing and setter cout << "--------- Test operator[] indexing ----------------------- -------" << endl; //cout << "l1[0] == " << l1[0] << endl; //assert(l1[0] == 1); //cout << "l1[2] == " << l1[2] << endl; //assert(l1[2] == 3); //cout << "l1[4] == " << l1[4] << endl; //assert(l1[4] == 0); //cout << "Iterate over l2:" << endl << l2 << endl; //for (int index = 0; index < l2.getSize(); index++) //{ // cout << " l2[" << index << "] == " << l2[index] << endl; //}
  • 26. //cout << endl; //l2[0] = 8; //cout << "ListType setter using operator[] l2[0] == " << l2[0] << endl; //assert(l2[0] == 8); //l2[4] = -7; //cout << "ListType setter using operator[] l2[4] == " << l2[4] << endl; //assert(l2[4] == -7); //l2[7] = 42; //cout << "ListType setter using operator[] l2[7] == " << l2[7] << endl; //assert(l2[7] == 42); // test bounds checking on operator[] // you should uncomment these to test, but you shouldn't leave them uncommented // should cause exit and error message //cout << l2[-5]; // should cause exit and error message //cout << l2[8]; cout << endl << endl; //----------------------------------------------------------------------- - // test out of scope, destructors should be called cout << "--------- main exiting scope, destructors should be invoked -----" << endl;
  • 27. // return 0 to indicate successful completion return 0; } /** * @author Jane Programmer * @cwid 123 45 678 * @class COSC 2336, Spring 2019 * @ide Visual Studio Community 2017 * @date February 15, 2019 * @assg Assignment 07 Operator Overloading * * @description Assignment 07 part 01, practice with operator overloading. * In this first part of assignment, you need to define a ListType class * and overload the indicated operators. This version of your class * will only support list of int values. You will turn this into a * class template in part 2 of the assignment. */ #include "ListType.hpp" // static member variables have to be initialized like this int ListType::nextListId = 1; /** default constructor * Initialize as an empty list. Initially we have no memory * allocated, and the size (and allocation size) are 0. */ ListType::ListType() { id = nextListId++;
  • 28. size = allocSize = 0; item = NULL; } /** constructor (empty) * Initialize as an empty list with indicated iniaial * size of memory allocated. * * @param allocSize The initialze size for the empty list. */ ListType::ListType(int allocSize) { id = nextListId++; size = 0; this->allocSize = allocSize; item = new int[this->allocSize]; } /** constructor (array) * Initialize a list using an array of items for the initial values * in the list. * * @param size The number of items in the array given for initialization. * @param items An array (pointer to base address) of items to initialize * this list with. */ ListType::ListType(int size, int* initItem) { id = nextListId++; this->size = size; this->allocSize = size; item = new int[this->size];
  • 29. // copy the items into this list for (int index = 0; index < this->size; index++) { item[index] = initItem[index]; } } /** destructor * The class destructor. Be good stewards of memory and make * sure that we free up memory allocated to hold our list items * by this object when it goes out of scope. We display some * information for debugging/tracking ListType destruction. */ ListType::~ListType() { cout << "ListType: <id=" << id << "> out of scope, size: " << size << " allocSize: " << allocSize << endl; // be a good memory manager, free up memory we have allocated if (item != NULL) { delete [] item; } } /** overload operator= * Overload the operator= assignment operator. Whenever one list * variable is assigned to another this operator is invoked. * * @param rhs The list on the right hand side of the assignment,
  • 30. the * contents of which is to be (deep) copied to this list contents. * * @returns ListType Returns a reference to this list, after contents * have been copied/assigned. */ const ListType& ListType::operator=(const ListType& rhs) { // only assign if not doing a self-assignment if (this != &rhs) { // copy the values from rightList into this list int newAllocSize = rhs.size; // if not enough space, grow our list if (this->allocSize < newAllocSize) { int* newItem = new int[newAllocSize]; delete [] item; item = newItem; this->allocSize = newAllocSize; } // copy the items from righ hand side into this list for (int index = 0; index < rhs.size; index++) { this->item[index] = rhs.item[index]; } this->size = rhs.size; } // return the object assigned return *this; }
  • 31. /** * @author Jane Programmer * @cwid 123 45 678 * @class COSC 2336, Spring 2019 * @ide Visual Studio Community 2017 * @date February 15, 2019 * @assg Assignment 07 Operator Overloading * * @description Assignment 07 part 01, practice with operator overloading. * In this first part of assignment, you need to define a ListType class * and overload the indicated operators. This version of your class * will only support list of int values. You will turn this into a * class template in part 2 of the assignment. */ #include <iostream> #include <sstream> using namespace std; #ifndef _LISTTYPE_H_ #define _LISTTYPE_H_ /** ListType abstract data type * This list type is "templatized" to support creating concrete lists of * any type of object. This list supports dynamic shrinking and growing * of its size as items are appended and removed from the list. * In addition, several operators are overloaded for convenience of * inserting, accessing and outputting the list to a stream.
  • 32. * * @value id A unique id, each list is assigned its own unique id * upon creation. * @value size The current size (an int) or number of items currently * contained in the list. * @value allocSize The actual amount of memory we currently * have allocated. * @value item A (pointer to an) array of items of our templated * <Type> we are holding in our list. */ class ListType { private: // initial allocSize, unless overridden in construction const int ALLOCATION_INCREMENT = 10; static int nextListId; // class variable, assign unique listid int id; int size; int allocSize; int* item; public: ListType(); // default constructor ListType(int allocSize); // empty constructor ListType(int size, int* items); // construct from array ~ListType(); // class destructor // getters // member functions // overloaded operators const ListType& operator=(const ListType& rightList); // I also gave you the copy operator };
  • 33. // need to include the template implementations here, if/when you templatize //#include "ListType.cpp" #endif // _LISTTYPE_H_