3

I see a function member in a c++ class:

class bar{
//..
}

class foo{
public:
    foo(){};
    //...
    operator bar(){
       return bar();
    }
}

it's not an operator overloading, can anyone explain it to me ?

Top-Master
  • 7,611
  • 5
  • 39
  • 71
DoctorX
  • 73
  • 4
  • 3
    `operator bar()` is a conversion operator to convert instances of `foo` to `bar`. [user-defined conversion function](https://en.cppreference.com/w/cpp/language/cast_operator) `return bar();` returns a default constructed instance of `bar()`. (This is a bit stupid conversion but correct concerning C++.) ;-) – Scheff's Cat Feb 06 '22 at 13:10
  • 1
    When providing such a conversion operator, carefully consider whether it should have the [`explicit`](https://en.cppreference.com/w/cpp/language/explicit) specifier or not. (In my experience, 9 times out of 10 it ought to have `explicit`.) – Eljay Feb 06 '22 at 14:14

1 Answers1

5

It is a user-defined conversion operator which constructs a bar object from the foo object. The purpose is to enable type casting from foo to bar.

nielsen
  • 5,641
  • 10
  • 27