What does the operator MyClass * () mean?

I have the following class definition:

struct MyClass { 
   int id;
   operator MyClass* () { return this; }
};

I am confused by what the line does operator MyClass* ()in the above code. Any ideas?

+4
source share
2 answers

This is a type conversion operator. It allows you to implicitly convert a type object MyClassto a pointer, without requiring the use of an address operator.

Here is 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
}

And why the transformation is determined, which is debatable. Honestly, I have never seen this in the wild, and I cannot guess why it was identified.

+7
source

This is a custom conversion that allows implicit or explicit conversion from a class type to another type.

cppreference :

:

- - , , :

operator conversion-type-id   (1) 

explicit operator conversion-type-id  (2) (since C++11)
  • ,

  • , .

+1

Source: https://habr.com/ru/post/1688751/


All Articles