0

I'm trying to return the result of operator+ to operator= but am getting a bogus value when returning *this in operator =; when calling rhs and accessing its functions the values are correct, but operator = is not sending out a copy of the class whats wrong?

 VecXd& operator=(const VecXd &rhs) { cout << rhs.vecArr[0] << " " << rhs.vecArr[1] << " " << rhs.vecArr[2] << " " << endl; return *this; } VecXd& operator+(const VecXd& rhs){ VecXd& result = *this; cout << "TEST FOR DIMENSION-> " << dimension << endl; if(result.dimension == rhs.dimension) //dimension level check { for(int i = 0; i < rhs.dimension; i++) { result.vecArr[i] += rhs.vecArr[i]; cout << result.vecArr[i] << " our new value" << endl; } cout << result << " result test!" << endl; return result; } else{ cout << "Dimensions do not match!!! Error!" << endl; } 

}

Help? thank you!

4
  • Just skimming your code, maybe you want VecXd &result = *this; instead of VecXd result = *this;? Commented Sep 19, 2013 at 2:46
  • I would also suggest looking at using assertions or exceptions instead of your if (dimension == rhs.dimension) check. If the code skips to else, the function no longer returns a value. Commented Sep 19, 2013 at 2:52
  • I implemented what you said, and noticed that the value operator= takes in (const VecXd& rhs) gives me the correct values when I access its functions using rhs. but returning from operator= is not returning the class? Commented Sep 19, 2013 at 3:06
  • 1
    Declaring result like this: VecXd &result = *this; would be right if you were implementing the += operator, but you are not. Commented Sep 19, 2013 at 3:14

1 Answer 1

2

You shold not return a reference to result. result is a local variable, and goes out of scope when exiting the method. You most likely want to return a copy of result, so change your operator return type:

VecXd operator+(const VecXd& rhs) const 

This will return a value of type VecXd and not a reference.

Oh, and since you are implementing the + operator, and not the += operator, you probably want to change this:

vecArr[i] += rhs.vecArr[i]; 

to this as well:

result.vecArr[i] = vecArr[i] + rhs.vecArr[i]; 

And there is probably no need to initialize result using *this

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

1 Comment

This is an answer to your question before you changed your example code. Now you have ended up implementing the += operator while calling it the + operator. Who ever reads your code or uses your class will hate you :-p

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.