Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit Conversion Operator Overloading syntax

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.

like image 303
vthulhu Avatar asked Apr 09 '26 12:04

vthulhu


1 Answers

operator int() is a conversion function that declares a user-defined conversion from A to int so that you can write code like

A a;
int x = a; // invokes operator int()

This is different from int operator()(), which declares a function-call operator that takes no arguments and returns an int. The function-call operator allows you to write code like

A a;
int x = a(); // invokes operator()()

Which 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.

like image 177
James McNellis Avatar answered Apr 12 '26 04:04

James McNellis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!