I have an assignment where I am supposed to be creating a class called SortedSet. It inherits from a class called IntList, which is a linked list class we created on a previous assignment. A SortedSet is an IntList where all the values are in ascending order and there are no duplicates. In the class, we are supposed to overload the operators "|" and "&." The "|" operator is the union of two SortedSets (all the values without duplicates in a new set) and the "&" makes the intersection (all the values that both sets have).
When the function for the operator is called, it has to create a new SortedSet object because it cannot modify the values on either side of the operator. However, when the object is out of scope, it calls the destructor, so when its returned, the pointers to the list (head and tail) no longer exists. For example, if I were to do something like SortedSet s3 = s1 | s2; when it returns the value of (s1 | s2), and tries to assign the value to s3, the list cannot be copied over because the pointers point to junk.
so anyways, what I am asking, is there a way to declare an object within a function that will not have the destructor called on it?
You can do this by creating the object with new and returning that.
However, for an overloaded operator, that would be inappropriate. No one would expect operator| to return a pointer.
Instead, just make sure the copy constructor makes a proper copy of the object. If NRVO can do its magic, that copy will never need to happen, though.
You don't need to dynamically allocate. Your set and list classes must implement a proper copy constructor and assignment operator so that your operator| can return by value. It is too bad that your teacher is asking you to reinvent the wheel though. std containers and algorithms already provide this functionality. You should be learning how to use the existing tools but instead you are being taught to reinvent the wheel. I think that it is a poor and illogical use of those operators. Merge and intersect algorithms do not align with the concept of logical OR and AND in my mind.