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 ??
?
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.
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.
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.
#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.
You can either use the name of the overloaded operator:
operator()(n-1);
or invoke the operator on the current object:
(*this)(n-1);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With