Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does operator MyClass*() mean?

Tags:

c++

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?

like image 225
kinjia Avatar asked Jan 30 '23 07:01

kinjia


1 Answers

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.

like image 103
StoryTeller - Unslander Monica Avatar answered Feb 12 '23 11:02

StoryTeller - Unslander Monica