Reputation: 93
so I have a copy constructor of a class over here...
template<class ItemType>
LinkedStack<ItemType>::LinkedStack(const LinkedStack<ItemType>& aStack)
{
// Point to nodes in original chain
Node<ItemType>* origChainPtr = aStack.topPtr;
if (origChainPtr == nullptr)
topPtr = nullptr; // Original stack is empty
else
{
// Copy first node
topPtr = new Node<ItemType>();
topPtr->setItem(origChainPtr->getItem());
// Point to last node in new chain
Node<ItemType>* newChainPtr = topPtr;
// Advance original-chain pointer
origChainPtr = origChainPtr->getNext();
// Copy remaining nodes
while (origChainPtr != nullptr)
{
// Get next item from original chain
ItemType nextItem = origChainPtr->getItem();
// Create a new node containing the next item
Node<ItemType>* newNodePtr = new Node<ItemType>(nextItem);
// Link new node to end of new chain
newChainPtr->setNext(newNodePtr);
// Advance pointer to new last node
newChainPtr = newChainPtr->getNext();
// Advance original-chain pointer
origChainPtr = origChainPtr->getNext();
} // end while
newChainPtr->setNext(nullptr); // Flag end of chain
} // end if
} // end copy constructor
And I did a simple program but my professor told me that I didn't use the copy constructor and I don't seem to find how to do it. All I got is this but it doesn't display the second object "lStack2".
Here is my main...
#include <iostream>
#include "LinkedStack.h"
using namespace std;
int main(){
int val1, val2, val3, val4;
LinkedStack<int> lStack1;
LinkedStack<int> lStack2;
lStack2 = lStack1;
cout << "Enter the first value: ";
cin >> val1;
cout << "Enter the second value: ";
cin >> val2;
cout << "Enter the third value: ";
cin >> val3;
cout << "Enter the fourth value: ";
cin >> val4;
lStack1.show();
lStack2.show();
return 0;
}
And here is my display function...
template <class ItemType>
void LinkedStack<ItemType>::show() const{
Node<ItemType>* entryPtr = topPtr;
while (entryPtr != nullptr){
cout << entryPtr->getItem() << endl;
entryPtr = entryPtr->getNext();
}
}
Can someone help to figure out how to implement the copy constructor?
Upvotes: 0
Views: 1358
Reputation: 1312
lStack2 = lStack1
will call the assignment operator. To use the copy constructor you actually need to construct the object (when declaring it):
LinkedStack<int> lStack2(lStack1);
or
LinkedStack<int> lStack2 = lStack1;
Upvotes: 2
Reputation: 74028
You have two stacks
LinkedStack<int> lStack1;
LinkedStack<int> lStack2;
and then assign the first to the second
lStack2 = lStack1;
This utilizes the assignment operator.
To use the copy constructor, you would rather say
LinkedStack<int> lStack2(lStack1);
Upvotes: 3