Assume i have a class:
class foo
{
....
//some constructors here set val=34
....
private:
int val;
int & foo::operator,()
{
return val;
}
};
and i want to be able to use it as:
foo bar;
printf(" %d ", bar); //i need to get value of bar.val
//with just using bar itself with
//using an overloading
//but , overloading does not work
//i need to get 34 without using bar.val
//i need this without any getter
//i need val to be private
Question: Is this kind of overloading possible? If yes, how?
I tried:
int foo::operator int()
{
return val;
}
but it says “return type may not be specifiet on a conversion function” 🙁
I tried:
operator int() const { return val; }
conversion works only outside of printf & cout.
int e=foo;
printf(" %d ",e); //works
You cannot overload a class, but you can use a conversion operator so that it will automatically convert to different types according to expected parameters in that context. In your case, as
valis anint, you’d overload the conversion tointlike this:Now wherever an
intis required, and you provide afoo, this conversion is applied.There are some limits. For example, if you pass
footo a function template where the type of the corresponding argument is generic, there will be no conversion in that place. The conversion also won’t affect other expressions which don’t enforce a type. As an example, iffis typefoo, then&fwill always be of typefoo*, notint*. For most practical applications, all this is exactly what you need. But I believe that the C-style variadicprintfis just such a case where there is no well-defined expected type. Better use a C++-style call, or an explicit caststatic_cast<int>(f).If neither is acceptable for you, then you are into trouble: there is no way that the C++ logic can deduce the fact that you require an
inthere, simply because you included a%din some string constants. The type conversion is a compile-time thing, whereas the interpretation of format strings is done at runtime (except when generating warnings the way e.g. gcc does). The compiler won’t know what type that argument needs to be, therefor it won’t know what conversion to execute, therefore you have to help him in some way.As long as this
int valis the only member offoo, and there are no virtual functions either in this class, and neithe ris there a base class with any data members or a virtula function, the memory layout of an object of classfoowill usually be the same as that of a plain integer. This means that the untyped C-styleprintfwon’t be able to tell the difference, even without any conversion at all. But relying on this is really bad style, so I’d advise against making use of this.