Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
753 views
in Technique[技术] by (71.8m points)

function overloading vs default argument in c++

Hi i have a confusion or to say more i need to understand something. I have a procedure and another overloaded procedure of same.

    string conct (string a, string b) {
      string str = conct(a, b, "string");
      return str;
    }

    string conct (string a, string b, const char* c) {
      // do the processing;
      return concatenated_string;
    }

is it possible that instead of having two overloaded functions, if i make c in the overloaded function as default argument. So that even if someone passes only two arguments, i can just have one function to handle that case.

But my main concern comes in the third argument which is currently const char* c. So if i make it to something like const char* c = "string", would it be correct way to handle the case of removing overloading with one function with default argument.

I saw the post here but that seems to be focused on compilation and not the confusion i have.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, you can replace your overloaded functions with one function and a default argument:

string conct (string a, string b, const char* c = "string") {
  // do the processing;
  return concatenated_string;
}
  • When you overload functions the compiler generates code for each function, probably resulting in larger code size.
  • If an overload just acts as a thin wrapper as in your case then the optimizer may eliminate the extra work.
  • default arguments get set at the caller's location, rather than inside the function, so default arguments must be publicly visible, and changing them requires recompiling all callers. With an overload like yours the psuedo-default argument becomes a hidden detail.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...