1

Please consider the following code:

#include <iostream>
using namespace std;

class vec {
  public:
    float x,y;

  vec(float a, float b) {
    x = a;
    y = b;
  }

  const vec operator + (const vec & a) {
    vec ResVec(0.0f, 0.0f);
    ResVec.x = x + a.x;
    ResVec.y = y + a.y;

    return ResVec;
  }

};

vec foo(const vec& v1, const vec& v2)
{
    const vec temp(2.0f,2.0f);
    return v1 + v2 + temp;
}

int main() {
  vec v1(1.0f, 1.0f);
  vec v2(2.0f,2.0f);
  vec v3(0.0f,0.0f);

  v3 = foo(v1,v2);
}

Run the above code online

I want to implement the function foo with const input parameters. But I fail, because the compiler says: error: no match for ‘operator+’ (operand types are ‘const vec’ and ‘const vec’) return v1 + v2 + temp. How can I modify the operator overloading so that I can use the + operator in the function

vec foo(const vec& v1, const vec& v2)

1
  • Change const vec operator + (const vec & a) to const vec operator + (const vec & a) const. It tells the compiler that this function does not change anything about the object from that it is called and then it can be called for const objects. Commented Dec 1, 2019 at 21:40

1 Answer 1

2
 const vec operator + (const vec & a) {

This overload returns a const vec. Not a vec. This is important.

     v1 + v2 + temp;

The first addition operator, thusly, returns a const vec. The second addition operator will attempt to add const vec to a vec. However the overload is not a const class method, so it can't be invoked for a const object (this is not a 100% technically accurate explanation, see below, but it's easier to understand in this example).

Simply change the overload as:

 const vec operator + (const vec & a) const {

That's what it should be anyway, since it doesn't modify anything in this. There are other reasons why this overload must be a const class method; it's easier to understand why, in this case, by considering the fact that const vec gets returned. You can also declare this overload as return a vec instead of a const vec, but that's not a material issue (the same compilation error will occur, for a different reason).

When it comes to declaring operator overloads, the following rule of thumb applies: if the overloaded operator does not modify anything in this, you must declare it as a const class method.

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.