I came across this code just few minutes back here in Stack Overflow.
I was confused about what actually operator int&() { return i; } is doing in the code.
#include <iostream>
#include <conio.h>
using namespace std;
class INT {
public:
INT(int ii = 0) : i(ii) {}
operator int&() { return i; }
void display()
{
cout << "value of i is : " << i;
}
private:
int i;
};
int main()
{
INT l;
cin >> l;
l.display();
getch();
return 0;
}
I added the display function just to get some insight. I saw that the value that I get from cin >> l; gets assigned to i which is private member of object l. So this is
some sort of overloading definitely I guess.
Can you let me know can we take the value of the object of class from directly through cin? Does it work fine?
What if I have two int variables in private part of my class INT?
It is a Conversion Operator; it takes in an
INTobject and returns a reference tointtype.One implicit conversion is always allowed whenever the compiler can match function arguments etc.
So, whenever there is a function which takes an
intbut anINTinstance is passed to it, the compiler uses this conversion operator to convert anINTtoint, so that appropriate conversion takes place and function can be called.As said in the first answer, this is useful whenever your code needs a lot of implicit conversions.
Note that in the absence of such a feature, one would have to provide special member functions which return appropriate types and the user will have to call them explicitly; this is lot of coding overhead, which is avoided by this feature.
In order that
cin>>lshould work,lshould be of a data type for which the>>operator is overloaded for typecin(istream)Note that
>>is overloaded for most of the built-in data types, and hence you can directly use,cin>>i, for types whereiisintorfloatand so on.However, in your example,
lis of the typeINTand>>operator is not overloaded for theINTdata type. Of courseINTis your custom class and the standard C++ library implementation could not know of it while implementing overloads for>>and hence no overload exists for it.Since there is no overloaded version of
>>available, you cannot directly use>>and the compiler will return an error of no matching function.You will have to provide an overload >> operator as an free standing function, receiving an
INT, to be able to usecin>>l.