Search code examples
c++oopclassint

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


Is there a (more or less at least) standard int class for c++?

If not so, is it planned for say C++13 and if not so, is there any special reasons?

OOP design would benefit from it I guess, like for example it would be nice to have an assignment operator in a custom class that returns an int:

int i=myclass;

and not

int i=myclass.getInt();

OK, there are a lot of examples where it could be useful, why doesn't it exist (if it doesn't)?

It is for dead reckoning and other lag-compensating schemes and treating those values as 'normal' variables will be nice, hopefully anyway!.


Solution

  • 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