Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an "operator int" function?

What is the "operator int" function below? What does it do?

class INT {    int a;  public:    INT(int ix = 0)    {       a = ix;    }     /* Starting here: */    operator int()    {       return a;    }    /* End */     INT operator ++(int)    {       return a++;    } }; 
like image 840
ankit Avatar asked Sep 28 '10 16:09

ankit


People also ask

What does int & operator do?

It is a Conversion Operator; it takes in an INT object and returns a reference to int type.

What are conversion operators in C++?

Conversion Operators in C++ C++ supports object oriented design. So we can create classes of some real world objects as concrete types. Sometimes we need to convert some concrete type objects to some other type objects or some primitive datatypes. To make this conversion we can use conversion operator.

What does a conversion operator do?

A conversion operator, in C#, is an operator that is used to declare a conversion on a user-defined type so that an object of that type can be converted to or from another user-defined type or basic type. The two different types of user-defined conversions include implicit and explicit conversions.

What is a conversion function give syntax?

Conversion function syntaxConversion functions have no arguments, and the return type is implicitly the conversion type. Conversion functions can be inherited. You can have virtual conversion functions but not static ones. Parent topic: User-defined conversions (C++ only)


2 Answers

The bolded code is a conversion operator. (AKA cast operator)

It gives you a way to convert from your custom INT type to another type (in this case, int) without having to call a special conversion function explicitly.

For example, with the convert operator, this code will compile:

INT i(1234); int i_2 = i; // this will implicitly call INT::operator int() 

Without the convert operator, the above code won't compile, and you would have to do something else to go from an INT to an int, such as:

INT i(1234); int i_2 = i.a;  // this wont compile because a is private 
like image 80
John Dibling Avatar answered Sep 24 '22 02:09

John Dibling


operator int() is a conversion operator, which allows this class to be used in place of an int. If an object of this type is used in a place where an int (or other numerical type) is expected, then this code will be used to get a value of the correct type.

For example:

int i(1); INT I(2); // Initialised with constructor; I.a == 2 i = I;    // I is converted to an int using `operator int()`, returning 2. 
like image 41
Mike Seymour Avatar answered Sep 24 '22 02:09

Mike Seymour