2

in this code:

    void AdptSendReply(const char* str)
{
    string s(strlen(str) + 2);
    s = str;
    AdptSendReply(s);
}

void AdptSendReply(const string& str)
{
    string s(str.length() + 2);
    AdptSendReply(s); // use the next one
}

void AdptSendReply(string& str)
{
    if (AdapterConfig::instance()->getBoolProperty(PAR_LINEFEED)) {
        str += "\r\n";
        AdptSendString(str);
    }
    else {
        str += "\r";
        AdptSendString(str);
    }
}

i think c++ use of overloading ability.but how it can recognize which of the two functions "void AdptSendReply(string& str)" or "void AdptSendReply(const string& str)" must use?!

2 Answers2

1

Calling overloading function triggers a process called overload resolution, which uses argument types to select the proper function to call

  • If you supply an lvalue argument of type string, the compiler will call void AdptSendReply(string& str) version.

    string s = "hello";
    AdptSendReply(s); // calls 'string& str' version
    
  • If you supply an lvalue argument of type const string, the compiler will call void AdptSendReply(const string& str) version.

    const string s = "hello";
    AdptSendReply(s); // calls 'const string& str' version
    
  • If you supply an rvalue argument, the compiler will call void AdptSendReply(const string& str) version.

    AdptSendReply(string("hello")); // calls 'const string& str' version
    

And so on. The full set of rules that govern overload resolution is quite extensive, especially when the context involves implicit conversions.


It is not clear what you mean by "must use". Normally, overloaded functions will do the same thing (functionality-wise), meaning that you are not supposed to worry about which function to use. Just call it with the argument you have available and the compiler will select the proper function to call.

Also, what is string? How are we supposed to know that? Without knowing it, your question make little sense.

0

The compiler decides which function to use based on the variable type information. Imagine you write

str += "test";

If you declare str as a constant, the above line will throw an error. So if you write AdptSendReply(str) instead, the compiler will call the const function. Likewise, if you declare str as a mutable variable, the above line will compile fine, and, should you call AdptSendReply(str), the compiler will use the non-const function.

Dmitry Grigoryev
  • 1,288
  • 11
  • 31