Problem 4
Add proper copy control to the template class List, that is, implement the copy constructor and the assignment operator:
• List( const List& aOtherList ),
• List& operator=( const List& aOtherList ).
The copy constructor initializes an object using aOtherList. This process requires two steps:
• Perform default initializing of object.
• Assign aOtherList to this object. Remember this object is “*this”.
The assignment operator overrides an initialized object. That is, the assignment operator must first free all resources and then copy the elements of aOtherList. Both steps are easy as you have already the necessary infrastructure. There is a convenient C++ idiom at your disposal. You can write, this->~List() to mean that you release all resources associated with this object, but do not delete this object itself. Remember, assignment must be secured against “accidental suicide.”
You can use #define P4 in Main.cpp to enable the corresponding test driver.
void testP4()
{
using StringList = List<string>;
string s1( "AAAA" );
string s2( "BBBB" );
string s3( "CCCC" );
string s4( "DDDD" );
string s5( "EEEE" );
List<string> lList;
cout << "Test of problem 4:" << endl;
lList.push_front( s4 );
lList.push_front( s3 );
lList.push_front( s2 );
List<string> copy( lList );
// iterate from the top
cout << "A - Top to bottom " << copy.size() << " elements:" << endl;
for ( const string& element : copy )
{
cout << element << endl;
}
// override list
lList = copy;
lList.push_front( s1 );
lList.push_back( s5 );
// iterate from the top
cout << "B - Bottom to top " << lList.size() << " elements:" << endl;
for ( auto iter = lList.rbegin(); iter != iter.rend(); iter-- )
{
cout << *iter << endl;
}
cout << "Completed" << endl;
}
The result should look like this:
Test of problem 4:
A - Top to bottom 3 elements: BBBB
CCCC
DDDD
B - Bottom to top 5 elements: EEEE
DDDD
CCCC
BBBB
AAAA
Completed
Students succeed in their courses by connecting and communicating with an expert until they receive help on their questions
Consult our trusted tutors.