swap class member function is corrupting data swapped c++

Viewed 48

I am making a template class of an array based list and there are some issues with data corruption that i am troubling with. I wanted it to have a swap member function that will receive a reference of another array list and it will swap the values, but there is data corruption.

#include<iostream>
#include<cstdlib>

using namespace std;

template<class type>
class arrayList{
    private:
        bool empty;
        type *list;
        int currentSize; //actualk currentSize of the array
        int maxSize; //Max amount of ellements that the arrat can have
        int elemCount;//element elemCount
    public:
        arrayList(){...}
        arrayList(int elemCount){...}
        ~arrayList(){...}
           ...
           ...
           ...
        void swap(arrayList<type> &al){
            arrayList<type> aux = al;
            al = *this;
            *this = aux;
        }
};

template<class T>
void swap(arrayList<T> &a, arrayList<T> &b){
    T aux = a;
    a = b;
    b = aux;
}

int main(){
    arrayList<int> al1, al2;
    al2.push(43);
    al2.push(4);
    al2.push(8);
    al2.push(734);
    for(int i = 0; i < 10; i++)
        al1.push(i * 3);
    //al2 = arrayList<int>(al1);
    
    al1.push(12);
    
    al1.resize(8);
    al1.print();

    al1.gap(5, 3);

    al1.print();
    //al1.insert(12, 7);
    
    //al1.print();
    /*
    al1.resize(8);
    al1.print();

    al1.erase(3);
    al1.print();
    al1.erase(9);*/

    al1.crease(3, 3);
    al1.print();

    al1.erase(7);
    al1.print();

    al1 = al1 + al2;
    al1.print();

    swap<arrayList<int>>(al1, al2);
    al1.print();
    al2.print();
    return 0;
}

the results are:

[0, 3, 6, 9, 12, 15, 18, 21]
[0, 3, 6, 9, 12, 0, 0, 0, 15, 18, 21]
[0, 3, 6, 0, 0, 15, 18, 21]
[0, 3, 6, 0, 0, 15, 18]
[0, 3, 6, 0, 0, 15, 18, 43, 4, 8, 734]
[43, 4, 8, 734]
[7499984, 7499328, 6, 0, 0, 15, 18, 43, 4, 8, 734]

as you can see there is a data corruption when i print the contents of al2 that is copying al1.

this is the original code: https://github.com/96Fetuchini/c-/blob/main/arrayBasedList.cpp

0 Answers
Related