How do I make the head of a linked list as a function parameter optional?
For example,
myFunction(node* head = node()) //does not work.
How do I make the head of a linked list as a function parameter optional?
For example,
myFunction(node* head = node()) //does not work.
Code:void myFunction(node *head = NULL) { if (head == NULL) // Whatever you need to do to take care of the head not being given. }
Is there another way to do it? Because I create the linked list by calling a function from main, (so head will not be null), but then I have main call another function that needs to recursively use the list...
Function overloading?Is there another way to do it?
I do not see how is this related to needing optional parameters without default arguments. You need to explain more, methinks.Because I create the linked list by calling a function from main, (so head will not be null), but then I have main call another function that needs to recursively use the list...
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
So in that scenario you don't want an optional parameter. In main, you would need to pass the head of the list that you just created into the function, and the recursive calls would use their own thing as appropriate.
Well, the head is a private variable inside a class... therefore, main does not have access to it... the functions that create and recursively use the list are members of the class...
If the functions that use the list are members of the class, then you need to be calling them from an instance of the class, no? And that instance of the class will be able to access the head just fine. So your function should be called like MyPrivateClass.doStuff(), and doStuff() can call another method doRecursiveStuff(list_head) or whatever.
Right, but the other member functions have access to the head, so what is the problem?Well, the head is a private variable inside a class... therefore, main does not have access to it... the functions that create and recursively use the list are members of the class...
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
tabstop: I can do that but I want main to give an overall picture of the program. If it is not possible it is not possible... I just like main to be my function caller.
And since in my scenario main does give an overall picture of the program (I'm assuming you have a more descriptive name in mind than "doStuff"), I fail to see the problem here.
In other words, people reading your main will see that X happens; that it happens recursively they would have to look at the class to discover. On the other hand, they shouldn't care whether it happens recursively or iteratively. (Unless they're your teacher, in which case they would be reading the whole code anyway so big deal.)