Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What guarantees that the overloaded non-const method is invoked?

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/how. I'd be worried that 2nd function would call itself, leaving me with out-of-control recursion until the stack is exhausted. Is this guaranteed to work?

like image 425
Stéphane Avatar asked May 01 '13 19:05

Stéphane


2 Answers

You have two overloaded functions:

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

What you're passing is a non const-qualified std::string. Therefore, the function that takes the non const-qualified argument is a better fit. If that didn't exist, the compiler could convert the non const-qualified string to a const-qualified string to make the call, but for function overloading a call that requires no conversion is a better fit than a call that requires a conversion.

like image 141
Jerry Coffin Avatar answered Sep 22 '22 09:09

Jerry Coffin


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

No. It is not recursion. It would invoke the other overload whose parameter is std::string &.

It is because the type of the expression s is std::string & which matches with the parameter type of the other overloaded function.

In order to recurse, the argument at call-site needs to convert into std::string const &. But in your case, this conversion is unnecessary as there exists an overload which doesn't require conversion.

like image 20
Nawaz Avatar answered Sep 25 '22 09:09

Nawaz