Reputation: 2002
I have a class named Dollars as
class Dollars
{
private:
int dollars;
public:
Dollars(){}
Dollars(int doll)
{
cout<<"in dollars cstr with one arg as int\n";
dollars = doll;
}
Dollars(Cents c)
{
cout<<"Inside the constructor\n";
dollars = c.getCents()/100;
}
int getDollars()
{
return dollars;
}
operator int()
{
cout<<"Here\n";
return (dollars*100);
}
friend ostream& operator << (ostream& out, Dollars& dollar)
{
out<<"output from ostream in dollar is:"<<dollar.dollars<<endl;
return out;
}
};
void printDollars(Dollars dollar)
{
cout<<"The value in dollars is "<< dollar<<endl;
}
int main()
{
Dollars d(2);
printDollars(d);
return 0;
}
In the above code if I remove the overloaded ostream operator then it goes to
operator int()
{
cout<<"Here\n";
return (dollars*100);
}
But on providing ostream overloading it does not go there.
My confusion
Why isn't there any return type for operator int() function as far as my understanding says that all functions in C++ should have a return type or a void except the constructors.
Instead of int can I provide some user defined datatype there ?
In what situation should I use this functionality ?
Upvotes: 1
Views: 393
Reputation: 206879
This type of operator is called a conversion function. In your case, it converts from Dollars
to int
. That syntax is standard, you cannot specify a return type (you've already stated the type).
You can make conversion operators for custom types if you want. You could have:
operator Yen() { ... }
operator Euro() { ... }
Then an instance of Dollar
could be converted implicitly to a Yen
or Euro
, using these functions, without needing a cast (or a constructor taking a Dollar
in the Yen
or Euro
classes).
Example from the "C++03" standard (§12.3.2/2):
class X {
// ...
public:
operator int();
};
void f(X a)
{
int i = int(a);
i = (int)a;
i = a;
}
C++11 allows conversion functions to be marked as explicit. In that case, the conversion function is only considered during direct-initialization. (This is in general a good thing to do to avoid unexpected conversion, especially for fundamental types.) The example in the standard for that is (§12.3.2/2):
class Y { };
struct Z {
explicit operator Y() const;
};
void h(Z z) {
Y y1(z); // OK: direct-initialization
Y y2 = z; // ill-formed: copy-initialization
Y y3 = (Y)z; // OK: cast notation
}
(And C++11 states that conversion functions cannot be declared static.)
Upvotes: 3