//Inserting a new subject into our subject array
void Grocery::insert(const string& itemName) {
if(m_used == m_capacity) {
cout<<"Grocery List is full. Cannot add any additional items."<<endl;
}
else {
m_groceryList[m_used] = itemName;
m_used++;
cout << "Item:" << itemName << " added to the grocery list." << endl;
}
}
void Grocery::deleteLast(){
if (m_used == 0){
cout <<"Grocery List Empty!" <<endl;
}
else{
m_used--;
cout <<"Item:" <<m_groceryList[m_used] <<" removed from grocery list." << endl;
m_groceryList[m_used] = "";
}
ostream& operator <<(ostream& os, const Grocery& rg) {
os << "m_capacity: " <<rg.m_capacity <<endl;
os << "m_used: " <<rg.m_used <<endl;
os << "Your list has selected the following items:" << endl << " | ";
for(int i=0;i<rg.m_used; i++) {
os <<rg.m_groceryList[i] + " | ";
}
return os << endl;
}
m_groceryList = source.m_groceryList;
Two different Grocery objects pointing to the same data. Each of those two will call delete on the data. This is very bad.
Basically, your copy constructor is wrong and so is your assignment. You're not copying the data. You're just copying the pointer. You need to copy the data.
Grocery& Grocery::operator=(Grocery source){
//note that the parameter is passed by copy, so it calls the copy constructor
swap(*this, source);
return *this;
}
friendvoid Grocery::swap(Grocery &a, Grocery &b){
using std::swap;
swap(a.m_capacity, b.m_capacity);
swap(a.m_used, b.m_used);
swap(a.m_groceryList, b.m_groceryList);
}
//all at once, if you prefer
Grocery& Grocery::operator=(Grocery source){
this->m_capacity = source.m_capacity;
this->m_used = b.m_used;
this->m_groceryList = source.m_groceryList; //yes, just the pointer (the copy-constructor already did the job)
//as we'll destroy `source' we don't care what it holds, except for
source.m_groceryList = nullptr; //avoid deleting the pointer twice
return *this;
}
now, for the copy constructor, copy each element one by one (like you would copy two arrays)