4

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?

3
  • 2
    It is a conversion operator Commented Nov 5, 2017 at 9:23
  • thanks ,I will view the link URL. Commented Nov 5, 2017 at 9:28
  • @kinjia "what the operator MyClass* () line does in the code above" - Nobody knows this except the author of the code.:) Commented Nov 5, 2017 at 9:52

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Whoever wrote this code probably tried to emulate references :P
@Rakete1111 - I know, right? If only C++ had them :P
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.