C++ Overloading the plus operator to add an element to an object

Viewed 251

Constructor for object

Set<T>::Set() {
    buckets = new forward_list<T>[9];
    numBuck = 9;
    numElem = 0;
    maxLoad = 9;
}

Overloading of plus operator

Set<T>::operator+(T elem){
    Set<T> res;
    return res;
}

I don't quite know where to begin with this. This overloaded operator add its parameter elem to a copy of *this and return the result. ex:

Set<char>setA;
Set<char>setB;

setA.Add('a')
setA.Add('b')
setA.Add('c')
// setA contains {'a','b','c'}
setB = setA + 'd'
// setB should now contain {'a','b','c','d'}

Any guidance?

edit: Clarified operator overload functionality

2 Answers

For the copy of *this, you can modify the definition of res to use the copy constructor.

Set<T> res(*this);

Adding the elem argument uses the same method you used for adding elements to setA.

res.Add(elem);

Since it looks like your code is managing a pointer, you will need to define your own destructor, to release the allocated memory.

Set<T>::~Set() {
    delete[] buckets;
}

You are also obligated to implement your own copy constructor and assignment operator, due to the Rule of Three. Your copy constructor would need to performs its own allocation, and the elements from the other Set need to be copied over.

Set<T>::Set(const Set<T> &other) {
    numBuck = other.numBuck;
    numElem = other.numElem;
    maxLoad = other.maxLoad;
    buckets = new forwardList<T>[numBuck];
    // ... add code to copy elements from other.buckets
}

The assignment operator can be implemented using the copy-swap idiom.

Set<T> & Set<T>::operator = (Set<T> other) {
    using std::swap;
    swap(*this, other);
    return *this;
}

To avoid needing to implement your own destructor / copy constructor / assignment operator methods, you can opt to represent your buckets with a vector rather than managing your own pointer.

    std::vector<forward_list<T>> buckets;

You can just make a copy function in the set, and use the Add function inside the overload. Demo code:

Set<T>::operator+(T elem)
{
    Set<T> result;
    result.Copy(*this);
    result.Add(elem);
    return result;
}

NOTE: Or you can follow @jxh's answer and use the default copy constructor. I would make a Copy function just to be explicit. :)

Related