2

I have an assignment to overload operator += so it adds new data to the list. List += data should therefore mean list=list+data, which is logically similar to what operator += does with basic types like int etc. I suck at linked lists, I've just figured out how to do it with functions, so I have no idea what to do in this case.

List& List::operator+=(const T& newData)
    {
        last_ = (!first_ ? first_ : last_->next_) = new Elem(newData);
        ++listSize_;
        return *this;
    };

where T is from template <typenameT> class List {...} "

Is this okay, I mean can I use code from function

List& addToList (const T& newData) {same code snippet}

, will it give me expected results? I don't think so, because it never uses operator itself in the code and that kinda confuses me.

As it's obvious I'm a beginner in coding, sorry for my bad cpp :)

1
  • Typically you should include a class template's argument list with the class name. That way the code would be more self-documenting, and you wouldn't have to give us the comment. Commented Dec 27, 2019 at 0:00

1 Answer 1

2

If you define operator+= for your class, calling it on instance of your class:

yourlist += somedata;

would be equal to call to any other method:

yourlist.operator+=( somedata );

it is just a syntactic sugar. So as you can see this is pretty much the same as any other member function (except it allows you to call it a special way). So implementing operator+= with a call of method addToList() or vice versa is perfectly fine.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.