Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively call a function object

How do I call a function object from within itself? Seems I cannot use this. Example:

class factorial {
  public:
  int operator()(int n) {
    if (n == 0)
      return 1;
    return n * ??(n-1);
  }
};

What do I place at ???

like image 735
r.v Avatar asked Jul 29 '13 15:07

r.v


People also ask

What does it mean to recursively call a function?

In programming terms, a recursive function can be defined as a routine that calls itself directly or indirectly. Using the recursive algorithm, certain problems can be solved quite easily.

What are recursive objects?

Objects can have other objects as attribute values. When an object of some class has an attribute value of that same class, it is a recursive object.

How do you call a recursive function in Javascript?

The syntax for recursive function is: function recurse() { // function code recurse(); // function code } recurse(); Here, the recurse() function is a recursive function. It is calling itself inside the function.


3 Answers

#include <iostream>

class factorial {
public:
  int operator()(int n) {
    if (n == 0)
      return 1;
    return n * (*this)(n-1);
  }
};

int main()
{
    std::cout << factorial()(5) << std::endl;
}

Works fine for me. Live example.

like image 118
dyp Avatar answered Sep 22 '22 09:09

dyp


You can either use the name of the overloaded operator:

operator()(n-1);

or invoke the operator on the current object:

(*this)(n-1);
like image 22
Mike Seymour Avatar answered Sep 20 '22 09:09

Mike Seymour


As DyP mentioned, you can call (*this)(n-1). However, it's odd to read, so you'd be better off splitting it out into a seperate calculate_factoral method and calling that instead

like image 40
Sean Avatar answered Sep 22 '22 09:09

Sean