-4

I am trying to overload the % operator in C++ to make it do division instead of modulo. For example, 5 % 4 should give me 1.25 after overloading.

But I get "nan". Why?

This is the code I tried (but I get nan as the answer):

#include <iostream>
using namespace std;

class Modulo {
   public:
   int x;
   Modulo(int a) {
       x = a;
   }

   float operator%(const Modulo& other) {
       float result = float(x / (float)other.x);
   }
};

int main()
{
    Modulo m1(5), m2(4);
    cout <<  m1%m2;
}
7
  • 10
    Your operator doesn't return anything. Please enable warnings on your compiler. Commented Aug 2 at 19:55
  • 3
    @Robert I agree except the problem is like a typo in the code, and better close it for that Commented Aug 2 at 20:10
  • 1
    What people mean by enable warnings, you will then get something like this : godbolt.org/z/5zfdzhvWz Commented Aug 2 at 20:15
  • 4
    @bruno -- "overload" is correct. Yes, the definition inside the class defines an operator, but the choice of which version of the operator to use depends on the types of the arguments, and that's overloading. 5 % 4 still calculates the remainder of integer division. Commented Aug 2 at 20:56
  • 5
    An aside: why would you want to overload the modulo operator to behave like division?? Mathematically, although there is a relationship between modulo and division, they are different operators because they have different effects. Commented Aug 2 at 22:57

1 Answer 1

4

Don't you get a warning or two when you compile your code? If not, you should really crank up the warning level. On gcc, it's -Wall for starters. This question has some background and details on C and C++ warnings.

The compiler tells you what's wrong:

robert:~$ gcc modulo.cpp
modulo.cpp: In member function ‘float Modulo::operator%(const Modulo&)’:
modulo.cpp:15:5: warning: no return statement in function returning non-void [-Wreturn-type]

You calculate result, but never do anything with it. With -Wall you'd also get a warning about the unused variable. Bottom line: there is no return value, and still you try to print it. At best you get nan, for me it just crashes and burns.

Add return result; to float operator%(const Modulo& other):

float operator%(const Modulo& other) {
    float result = float(x / (float) other.x);
    return result;
}

Besides that, don't use this code in real life: it's very confusing to redefine the modulo operator to do division. There's a / operator for that. You'll confuse the heck out of yourself and your peers. Unrelated, but also important: get in the habit of consistently indenting your code. It makes it much easier to read. And enable all compiler warnings.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.