What ensures that an overloaded non-const method is called?

Given these 2 functions that modify and return a string:

// modify the original string, and for convenience return a reference to it std::string &modify( std::string &str ) { // ...do something here to modify the string... return str; } // make a copy of the string before modifying it std::string modify( const std::string &str ) { std::string s( str ); return modify( s ); // could this not call the "const" version again? } 

This code works for me using GCC g ++, but I don't understand why and how. I would be worried that the 2nd function will call itself, leaving me without recursion until the stack is exhausted. Is it guaranteed?

+8
c ++ recursion signature
source share
3 answers

You have two overloaded functions:

 std::string &modify( std::string &str ) std::string modify( const std::string &str ) 

What you're going through is non-competitive std::string . Therefore, a function that takes an argument other than const is better suited. If this was not the case, the compiler could convert a string not associated with a constant to a string with content to make a call, but for a call overload function that does not require conversion, it is better than a call that requires conversion.

+9
source share
 return modify( s ); // could this not call the "const" version again? 

Not. Recursion is not . It will refer to another overload with the std::string & parameter.

This is because the type of the expression s is equal to std::string & , which corresponds to the type of the parameter of another overloaded function.

To perform a repeat, the argument on the call site must be converted to std::string const & . But in your case, this conversion is not required , since there is an overload that does not require conversion.

+3
source share

This is not recursion, but overload. When you call the second function, the argument included in it is a constant string. Inside this function, you call another function that takes a non-constant string. What you do is stripping the string constant, and the best way to do this is to use const_cast.

stack overflow .

+1
source share

All Articles