1

Is there a way to overload operator/() to use the class as the denominator?

Like so: int foo = 5 / object;

Dasaru
  • 2,628
  • 5
  • 24
  • 25
  • 2
    This excellent SO post on [operator overloading](http://stackoverflow.com/questions/4421706/operator-overloading) includes good information about implementing binary arithmetic operators. – Blastfurnace Jul 21 '12 at 02:33

3 Answers3

4

Use a free function:

int operator/ (const int, const MyClass &);

If it needs to access private members that you have no interface for, make it a friend inside your class as well:

friend int operator/ (const int, const MyClass &);
chris
  • 58,138
  • 13
  • 137
  • 194
  • What exactly is a free function? I've never heard of it before. – Dasaru Jul 21 '12 at 02:36
  • @Dasaru, One that's not enclosed in a class. In this case, it being a member function constrains it to take a `MyClass *` as the first argument, leaving one open. The order of arguments corresponds to the way you call it, so it's impossible to switch them if it's in the class. – chris Jul 21 '12 at 02:36
  • @Dasaru: You'll also see them called `non-member` functions. – Blastfurnace Jul 21 '12 at 02:37
3

Use a free function instead of a member function for operator/.

Binary operators typically have the same operand types. Assuming that foo has a non-explicit constructor taking an int, you would have:

struct foo
{
  foo(int i) {};
};

int operator/(foo const& x, foo const& y);
mavam
  • 11,794
  • 10
  • 50
  • 86
0

Free function is your friend:

int operator/ (int, const MyClass &);
iTayb
  • 11,765
  • 23
  • 78
  • 132