BlueTune
BlueTune

Reputation: 1053

Using operator overloading inside a function with const type input parameters in c++

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)

Upvotes: 1

Views: 187

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118445

 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.

Upvotes: 2

Related Questions