Greetings,
Through a long debug session, I have discovered why your array seems to zero out. Let's just say, its nothing new ;) Personally, it was the unionOfIntegerSets() and intersectionOfIntegerSets() calls, but don't worry this can be fixed.
It is quite simple. As one may know, returning local variables always perform data loss. If we create a pointer to the data, we can temporarily save the data while passing through the function.
Our first and foremost step is to change the function declaration. Since we are going to return a pointer-type variable, we will need to add the * operator. The unary operator "*" is in [i]indirection of dereferencing[i] operator; when applied to a pointer, it accesses the object the pointer points to.
Inside the class, we must modify our function call to the following:
IntegerSet *unionOfIntegerSets( const IntegerSet& );
The green shows what has been modified. Please note, do the same withintersectionOfIntegerSets()
Secondly, down below we must change our code to:
IntegerSet *IntegerSet::unionOfIntegerSets( const IntegerSet &r ) {
IntegerSet temp(size > r.size ? size : r.size);
IntegerSet *p = &temp; // Pointer
p->emptySet();
int iterations = ( size < r.size ? size : r.size );
for ( int i = 0; i < iterations; i++ )
if ( set[ i ] == 1 || r.set[ i ] == 1 )
p->set[ i ] = 1;
return p;
}
A lot of stuff to digest, so let's explain this in greater detail.
We know about the return-type. Next we setup temp(), just the way it was done previously; now we create another IntegerSet called p. p is a pointer, and *p is the object of the pointer. The reason p equals "&temp" is because we are sending the address of temp to p.
If this makes sense, we are storing any information temp has inside p. The & operator only applies to objects in memory: variables and array elements. It cannot be applied to expressions, constants, orregister variables.
Now any further calls that used to call on temp must use p instead. Remember, if p is a pointer to structure, we would call on the structures members as the following:
p->member-of-structure
If you compile your code as of now, you may retrieve errors. The last thing to fix up is your call in main():
c = *a.unionOfIntegerSets( b );
The reason we added the * operator is because we want the data object of our returned data, not the memory address.
If you have further questions, please feel free to ask.
Hope this helps,
-Stack Overflow