kinjia
kinjia

Reputation: 41

What does operator MyClass*() mean?

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?

Upvotes: 4

Views: 778

Answers (2)

msc
msc

Reputation: 34578

It is a user-defined conversion which is allow implicit or explicit conversion from class type to another type.

cppreference reference:

Syntax :

Conversion function is declared like a non-static member function or member function template with no parameters, no explicit return type, and with the name of the form:

operator conversion-type-id   (1) 

explicit operator conversion-type-id  (2) (since C++11)
  1. Declares a user-defined conversion function that participates in all implicit and explicit conversions

  2. Declares a user-defined conversion function that participates in direct-initialization and explicit conversions only.

Upvotes: 1

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.

Upvotes: 7

Related Questions