After declaring a default constructor for this templated program I am working on:
template<typename T>
Set<T>::Set()
: size(0), capacity(8) {
//allocate new array
items = new T[capacity];
}
I have a relatively inconspicuous function contains that tests for whether or not items contains a specific item in it.
template<typename T>
bool Set<T>::contains(const T& item) const {
for (int i = 0; i < size; i++) {
if (this->items[i] == item)
return true;
}
return false;
}
It works fine when I call it in certain locations such as this function that reads through items and only adds an item if there is no other copy (part of our assignment specifications):
template<typename T>
void Set<T>::add(const T& item) {
if (this->contains(item) == 0) {
grow();
items[size++] = item;
}
}
But when I call it when attempting to overload the operator ==, I get the error in the title when I run it through DRMemory
template<typename T>
bool Set<T>::operator==(const Set<T>& other) const {
int count = 0;
for (int i = 0; i < size; i++) {
if (this->contains(other.items[i])) {
count++;
}
}
if (count == size)
return true;
return false;
}
sizeshould beother.size. Otherwiseother.items[i]in the loop may be out-of-bounds ifsize > other.size.Similarly
sizein the later check needs to beother.sizeas well.On the other hand, you need to add a test for
size == other.sizeanyway to make sure that the sets are really equal. If you put that at the beginning, it won't matter whether you usesizeorother.sizelater.Btw. instead of using
countto count the identical elements, you can justreturn falseas soon as one.containsfails.