Recursive class member function

hi. In order to call a member function recursively, what is the syntax? for example:
class foo
void recursiveCall ();

void foo::recursiveCall ();
recursiveCall ();  //here: how would you call this function again? I think you would need an object....but I'm not exactly sure...

Thank you
Try this
your code didn't post...
That would cause the function to loop I believe, the function gets called and it calls itself. Nothing to stop it calling itself again.
Last edited on
If you have a recursive function that doesn't need access to class member data than you can use a static member function.

Then foo::recursiveCall() would call it with no need for an object.
what if it does need access to the class member data?
You have a syntax error on line 7 with that extra semicolon, but otherwise I think it works as written (the call, at least - the infinite recursion is another matter).
If it needs access to class member data than a standard non-static member function is fine.

Of course you will need an object to call it. This can be the current object. A non-static member function can be considered the same as the static one except that there is a (hidden) extra argument to the function. This hidden argument is a pointer to the current object.

You can call it recursively with with just recursiveCall() as you have done. Or to make it clear you can use
this->recursiveCall() which is the same thing.

Since the class member data is accessed via pointer it is the same data for every function call. Data passed as arguments by value get a new copy for each recursive call and this can be part of the way a recursive algorithm works.
perfect, thanks for the answers i got the program to do what i wanted.
Topic archived. No new replies allowed.