Why was function overloading added to C++?

前端 未结 6 1884
囚心锁ツ
囚心锁ツ 2021-02-03 21:03

I have a C background. I was just wondering why was function overloading added to C++? C doesn\'t have function overloading but C++ does, what was the need for it?

What

6条回答
  •  有刺的猬
    2021-02-03 21:39

    It increases maintainability. If you have a type T and you call a function with it, then you need to change T, if the function has been overloaded for the new T then you can recompile instantly. In C you would have to go back and dig through all the call sites and change the function called. Take sqrt(). If you want to sqrt() a float, then you have to change to sqrtf().

    Not just that, but the volume and complexity of C++'s type system is far more than in C, and having to have separate function names for every possible overload would quickly exhaust the reasonable pool of names for functions that serve the same purpose but take different arguments, because now there's a lot more arguments to take.

    For example, compare the C and C++ string libraries. The C string library offers one method to append to a string - strcat(). C++'s std::string::append has eight overloads. What do you want to call them? append_a, append_b, etc? That's ridiculous- they all serve the same function, just in different ways.

    Edit: It is actually worth mentioning that append is a really bad example, many of the C++ string overloads are very redundant. However, this is more general case than that and not all of those overloads redundant.

提交回复
热议问题