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++; } };
It is a Conversion Operator; it takes in an INT object and returns a reference to int type.
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.
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.
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)
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With