Can i have a const function that is recursive in my class ?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes.
constcan always callconstfunctions again. You don’t even need mutable variables for it to make sense, for example you can pass things by reference into the recursive function and modify those for your state. (Or static variables, or non-members, or other functions which return non-const references or pointers to non-const things….)Minimal “useful” example (inspired by flownt’s comment on the other answer) traversing a linked list. (Recursion isn’t a great way of doing linked list traversal normally though)
You can also avoid the using the reference for the result, as appropriate for your problem, by re-writing
sum():