Question

I'm currently working on an assignment (so I'd rather no post the full code) trying to implement a Bag abstract data type.

Below is a method which I am currently trying to implement:

template <typename T>
Bag<T> Bag<T>::operator+ (const Bag<T>& bag) {
    int sizeofCurrentMultiset = cardinality_;
    int sizeofPassedMultiset  = bag.cardinality_;
    int totalSize = sizeofCurrentMultiset + sizeofPassedMultiset;

    Bag<T> newBag(totalSize);

    for (int i = 0; i < sizeofCurrentMultiset; i++) {
        newBag.insert(array_[i]);
    }

    for (int i = 0; i < sizeofPassedMultiset; i++) {
        newBag.insert(bag.array_[i]);
    }

    return newBag;
}

I'm storing the elements as a dynamic array.

My problem is that when the new bag is returned, I can print the cardinality fine (prints to 4, the original bags had two elements each), but the dynamic array doesn't contain the numbers (it prints out some random numbers such as -1789102). However when I try print out the elements before the bag is returned, it prints out fine.

No doubt it will be something trivial, but I'd appreciate the help.

Thanks.

Was it helpful?

Solution

You need to write a copy constructor for your Bag class. Looks like you are getting the default constructor which only does a shallow copy of your class. This is why the cardinality member is ok but your dynamic array is not. The copy constructor is called when your operator+ function returns the Bag object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top