Question

I am writing a operator function for - where my class object is a dynamic array of integer. the operator takes lhs and rhs object and return an object which is the set of elements in lhs but not in rhs.

though I have written the function but I am not able to return the set since the destructor is called right after the object is returned.

IntegerSet & IntegerSet::operator - (IntegerSet & rhs) const
{
    IntegerSet temp(capacity);//local object created to store the elements same size as lhs

    int k=0;
    int lhssize = ElementSize();//no. of elements in the set
    int rhssize = rhs.ElementSize();

    for (int i=0;i<lhssize;i++)
    {
        for (int j=0;j<rhssize;j++)
        {
            if (rhs.ptr[j]!=ptr[i])
            {
                k++;
            }
        }

        if(k==rhssize)
        {
            temp = temp + ptr[i];
        }
        k=0;
    }
    return temp;
}

and here is the constructor if you cannot understand the object

IntegerSet::IntegerSet(const int & size)//works correctly
{
    capacity = size;
    ptr = new int [capacity]();
}

IntegerSet::IntegerSet(const int & size)//works correctly
{
capacity = size;
ptr = new int [capacity]();

}

IntegerSet::IntegerSet(const IntegerSet & copy) : capacity(copy.capacity)//works correctly
{

ptr = copy.clonemaker();
}

IntegerSet::~IntegerSet()
{
capacity = 0;
delete [] ptr;
}


int * IntegerSet::clonemaker() const // works correctly
{
if(ptr==NULL)
{
    return NULL;
}

int *tempptr = new int [capacity];
for(int i=0;i<capacity;i++)
{
    tempptr[i]=ptr[i];
}

return tempptr;

}
Was it helpful?

Solution 2

You need to change to return the result by value.

IntegerSet IntegerSet::operator - (IntegerSet & rhs) const

Also it would make more sense to supply rhs by const reference when taking a second look.

OTHER TIPS

You'll have to return by value. The local object will be destroyed when the function returns, and there's no way to prevent that.

For that to work, your class will have to correctly follow the Rule of Three to make sure it's correctly copyable. In C++11 or later, you might also consider making it movable, to avoid unnecessary memory allocation and copying (although, in this case, the copy should be elided anyway).

Better still, follow the Rule of Zero and store a vector<int>, which will do all this for you, rather than trying to juggle raw pointers.

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