10

For the sake of clarity Let my new class be:

class MyInt{ public: MyInt(int x){theInt = x /10;} int operator+(int x){return 10 * theInt + x;} private int theInt; }; 

let's say I want to be able to define:

MyInt Three(30); int thirty = Three; 

But in order to get this result I'm writing:

MyInt Three(30); int thirty = Three + 0; 

how can I get automatic conversion from my Custom class to a built-in type?

1
  • 2
    Remark: it's usually a bad idea to have both conversions implicit (here int->MyInt via the non-explicit constructor and MyInt->int via a conversion operator). (Consider for example std::string, for which there is an implicit conversion from const char* (converting constructor) but not to const char* (for this you need to call .c_str() or related member functions).) [Also, typo: private -> private:] Commented Aug 30, 2013 at 13:58

1 Answer 1

19

With a type conversion function:

class MyInt{ public: MyInt(int x){theInt = x /10;} int operator+(int x){return 10 * theInt + x;} operator int() const { return theInt; } // <-- private int theInt; }; 
Sign up to request clarification or add additional context in comments.

5 Comments

With the added note that doing this should be transparent. That is, if you are converting to an int, the class should be a numeric class and not some custom class that does something totally unrelated.
It should be const (but operator+ too, if not a non-member function), and should probably return 10 * theInt according to OP's weirdness.
@gx_ thanks, I agree about const. I'll let OP do the arithmetic :)
how about more complex types, like std::vector<int> or std::vector<std::tuple<int, long>>? how do i determine what operator i should write? can you give some examples?
@qkhhly You can't write conversion operators from standard library classes (vector, etc) if that's what you mean. From a custom class written by you to a vector? Well, nothing special about them. The name of the type conversion function is the target type, so for example operator std::vector<int>() { /* code here */ }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.