0

How would I overload the = operator in a way that I could execute

int someInt;
MyClass instanceOfMyClass;
someInt = instanceOfMyClass;

Where MyClass contains an integer named number?

1
  • 4
    If you want it to be that transparent, how about a conversion operator? Commented Mar 29, 2013 at 5:21

2 Answers 2

2

You can't overload the operator= for the type int. What you are really looking for is the conversion operator operator int() for your MyClass. In your case, considering x to be the private member of your class:

operator int() { return x; }
Sign up to request clarification or add additional context in comments.

Comments

0

I would avoid doing this in most cases as it can be difficult to tell what exactly is happening. That said:

class MyClass {
 public:
  operator int() { return number; }

 private:
  int number;
};

This creates an (implicit) conversion operator for your class.

2 Comments

The only reason I'm doing it with this class is because the class is a random number generator. The integer of the class is the actual random number.
Why not use a normal method? NextRandomNumber() or something? It's possible doing this will obscure what the call does for no real benefit other than feeling clever.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.