function overloading vs default argument in c++

前端 未结 2 1134
攒了一身酷
攒了一身酷 2020-12-18 14:55

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         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-18 15:30

    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.

提交回复
热议问题