2012-01-08

C++ operator definitions inside and outside the class are not equivalent

This blog post presents some example code which demonstrates that having an operator outside a class is not equivalent to having it inside the class. As shown below, some implicit casts are applied only if the operator definition is outside the class.

It compiles when the operator definition is outside:

class C {
 public:
  C(unsigned a) {}
  C operator^(const C& masik) {
    return *this;
  }
 private:
  C();
};

int main() {
  C a = 5;
  unsigned b = 6;
  a ^ b;
  (C)b ^ a;
  b ^ a;  // Does not compile.
  return 0;
}

It compiles if the operator definition is outside:

class C {
 public:
  C(unsigned a) {}
 private:
  C();
};

C operator^(const C& a, const C& b) {
  return a;
}

int main() {
  C a = 5;
  unsigned b = 6;
  a ^ b;
  b ^ a;
  return 0;
}

No comments:

Post a Comment