Is there a standard 'int class' in c++?

If you want to allow your class to implicitly convert to int, you can use an implicit conversion operator (operator int()), but generally speaking implicit conversions cause more problems and debugging than they solve in ease of use.


it would be nice to have an assignment operator in a custom class that returns an int

You can do that with a conversion operator:

class myclass {
    int i;
public:
    myclass() : i(42) {}

    // Allows implicit conversion to "int".
    operator int() {return i;}
};

myclass m;
int i = m;

You should usually avoid this, as the extra implicit conversions can introduce ambiguities, or hide category errors that would otherwise be caught by the type system. In C++11, you can prevent implicit conversion by declaring the operator explicit; then the class can be used to initialise the target type, but won't be converted implicitly:

int i(m);    // OK, explicit conversion
i = m;       // Error, implicit conversion

Tags:

C++

Oop

Int

Class