I’m an intermediate C++ user and I encountered the following situation. The class definition shown below compiles fine with a g++ compiler. But I cannot put my finger on what exactly the whole syntax means.
My guess is that the function operator int() returns an int type.
Moreover, I cannot figure out how to use the overloaded operator () in main()
class A
{
public:
A(int n) { _num = n; } //constructor
operator int();
private:
int _num;
};
A::operator int() // Is this equivalent to "int A::operator()" ??
{
return _num;
}
int main()
{
int x = 10;
A objA(x); //creating & initializing
// how to use operator() ?
// int ret = objA(); // compiler error when uncommented
return 0;
}
Any help will be appreciated.
operator int()is a conversion function that declares a user-defined conversion fromAtointso that you can write code likeThis is different from
int operator()(), which declares a function-call operator that takes no arguments and returns anint. The function-call operator allows you to write code likeWhich one you want to use depends entirely on the behavior that you want to get. Note that conversion operators (e.g.,
operator int()) can get invoked at unexpected times and can cause pernicious errors.