I have the following class definition:
struct MyClass {
int id;
operator MyClass* () { return this; }
};
I'm confused what the operator MyClass* ()
line does in the code above. Any ideas?
It's a type conversion operator. It allows an object of type MyClass
to be implicitly converted to a pointer, without requiring the address-of operator to be applied.
Here's a small example to illustrate:
void foo(MyClass *pm) {
// Use pm
}
int main() {
MyClass m;
foo(m); // Calls foo with m converted to its address by the operator
foo(&m); // Explicitly obtains the address of m
}
As for why the conversion is defined, that's debatable. Frankly, I've never seen this in the wild, and I can't guess as to why it was defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With