0

I'm working on a project where I need to add two objects together by overloading the addition operator, 99% of it makes sense to me, but I can't figure out how to do the actual addition process.

My code is currently

Time operator+(const Time& t1)
{
     int num = this.milliseconds + t1.milliseconds;
     Time t(num);
     return t;
}

Then I call it like so

t4 = t1 + t2;

I thought using this.milliseconds would allow me to access t1's int variable but it won't allow me.

Basically my question is how do I access the time variable on the left of the + operator since I only pass the operator+ function one object of Time? (t2)

4
  • this is a pointer Commented Sep 23, 2017 at 23:13
  • The code you show should work if you just remove this., if it is part of the Time class. You should make that member function const, or better, make it a free function of two arguments using the class' operator+=. Commented Sep 23, 2017 at 23:14
  • Also, instead of defining a local variable and returning that, just construct a Time instance directly in the return statement, e.g. return {num};. Commented Sep 23, 2017 at 23:16
  • Also, as part of conditioning yourself to use good programming practices as a matter of course, make that num a const variable. Commented Sep 23, 2017 at 23:17

1 Answer 1

2

If your operator+ is a member function of the Time class then you should be able to access its fields when you change this.milliseconds to this->milliseconds or just milliseconds. Please note that this is a pointer so it requires the -> operator.

You don't have to be concerned about the operator+ having only one parameter. If you overload a two argument operator as a class member then it is implicitly assumed that the first argument of the operator is this.

You have also a possibility to overload an operator as a non-member function and then you have to specify two parameters like this: Time operator+(const Time& t1, const Time& t2).

It is also worth mentioning that your operator+ could be a const member function.

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.